Repository: rust-embedded/rust-raspi3-tutorial Branch: master Commit: 644474cc09f7 Files: 1175 Total size: 4.0 MB Directory structure: gitextract_d1imolyg/ ├── .editorconfig ├── .githooks/ │ └── pre-commit ├── .github/ │ ├── FUNDING.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── build_rpi3.yml │ ├── build_rpi4.yml │ ├── sanity.yml │ ├── test_integration.yml │ ├── test_unit.yml │ └── test_xtra.yml ├── .gitignore ├── .prettierignore ├── .prettierrc.json ├── .rubocop.yml ├── .ruby-version ├── .rustfmt.toml ├── .vscode/ │ └── settings.json ├── 00_before_we_start/ │ ├── README.CN.md │ ├── README.ES.md │ └── README.md ├── 01_wait_forever/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.ES.md │ ├── README.md │ ├── build.rs │ └── src/ │ ├── _arch/ │ │ └── aarch64/ │ │ └── cpu/ │ │ ├── boot.rs │ │ └── boot.s │ ├── bsp/ │ │ ├── raspberrypi/ │ │ │ └── kernel.ld │ │ └── raspberrypi.rs │ ├── bsp.rs │ ├── cpu/ │ │ └── boot.rs │ ├── cpu.rs │ ├── main.rs │ └── panic_wait.rs ├── 02_runtime_init/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.ES.md │ ├── README.md │ ├── build.rs │ └── src/ │ ├── _arch/ │ │ └── aarch64/ │ │ ├── cpu/ │ │ │ ├── boot.rs │ │ │ └── boot.s │ │ └── cpu.rs │ ├── bsp/ │ │ ├── raspberrypi/ │ │ │ ├── cpu.rs │ │ │ └── kernel.ld │ │ └── raspberrypi.rs │ ├── bsp.rs │ ├── cpu/ │ │ └── boot.rs │ ├── cpu.rs │ ├── main.rs │ └── panic_wait.rs ├── 03_hacky_hello_world/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.ES.md │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ └── cpu.rs │ │ ├── bsp/ │ │ │ ├── raspberrypi/ │ │ │ │ ├── console.rs │ │ │ │ ├── cpu.rs │ │ │ │ └── kernel.ld │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ └── print.rs │ └── tests/ │ └── boot_test_string.rb ├── 04_safe_globals/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ └── cpu.rs │ │ ├── bsp/ │ │ │ ├── raspberrypi/ │ │ │ │ ├── console.rs │ │ │ │ ├── cpu.rs │ │ │ │ └── kernel.ld │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ └── synchronization.rs │ └── tests/ │ └── boot_test_string.rb ├── 05_drivers_gpio_uart/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ └── cpu.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── console.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ └── synchronization.rs │ └── tests/ │ └── boot_test_string.rb ├── 06_uart_chainloader/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.md │ ├── build.rs │ ├── demo_payload_rpi3.img │ ├── demo_payload_rpi4.img │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ └── cpu.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ └── synchronization.rs │ ├── tests/ │ │ └── chainboot_test.rb │ └── update.sh ├── 07_timestamps/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ ├── cpu.rs │ │ │ └── time.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ ├── synchronization.rs │ │ └── time.rs │ └── tests/ │ └── boot_test_string.rb ├── 08_hw_debug_JTAG/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ ├── cpu.rs │ │ │ └── time.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ ├── synchronization.rs │ │ └── time.rs │ └── tests/ │ └── boot_test_string.rb ├── 09_privilege_level/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ ├── cpu.rs │ │ │ ├── exception/ │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ └── time.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── exception/ │ │ │ └── asynchronous.rs │ │ ├── exception.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ ├── synchronization.rs │ │ └── time.rs │ └── tests/ │ └── boot_test_string.rb ├── 10_virtual_mem_part1_identity_mapping/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.CN.md │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ ├── cpu.rs │ │ │ ├── exception/ │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ └── translation_table.rs │ │ │ │ └── mmu.rs │ │ │ └── time.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ ├── memory/ │ │ │ │ │ └── mmu.rs │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── common.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── exception/ │ │ │ └── asynchronous.rs │ │ ├── exception.rs │ │ ├── main.rs │ │ ├── memory/ │ │ │ ├── mmu/ │ │ │ │ └── translation_table.rs │ │ │ └── mmu.rs │ │ ├── memory.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ ├── synchronization.rs │ │ └── time.rs │ └── tests/ │ └── boot_test_string.rb ├── 11_exceptions_part1_groundwork/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── build.rs │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ ├── cpu.rs │ │ │ ├── exception/ │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── exception.s │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ └── translation_table.rs │ │ │ │ └── mmu.rs │ │ │ └── time.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ ├── memory/ │ │ │ │ │ └── mmu.rs │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── common.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── exception/ │ │ │ └── asynchronous.rs │ │ ├── exception.rs │ │ ├── main.rs │ │ ├── memory/ │ │ │ ├── mmu/ │ │ │ │ └── translation_table.rs │ │ │ └── mmu.rs │ │ ├── memory.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ ├── synchronization.rs │ │ └── time.rs │ └── tests/ │ └── boot_test_string.rb ├── 12_integrated_testing/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ └── boot.s │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── null_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ └── boot.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ └── translation_table.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ └── libraries/ │ ├── test-macros/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── test-types/ │ ├── Cargo.toml │ └── src/ │ └── lib.rs ├── 13_exceptions_part2_peripheral_IRQs/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── null_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ └── translation_table.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ └── libraries/ │ ├── test-macros/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── test-types/ │ ├── Cargo.toml │ └── src/ │ └── lib.rs ├── 14_virtual_mem_part2_mmio_remap/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── null_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ ├── mapping_record.rs │ │ │ │ │ ├── page_alloc.rs │ │ │ │ │ ├── translation_table.rs │ │ │ │ │ └── types.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ └── libraries/ │ ├── test-macros/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── test-types/ │ ├── Cargo.toml │ └── src/ │ └── lib.rs ├── 15_virtual_mem_part3_precomputed_tables/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── kernel_virt_addr_space_size.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── null_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ ├── mapping_record.rs │ │ │ │ │ ├── page_alloc.rs │ │ │ │ │ ├── translation_table.rs │ │ │ │ │ └── types.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ ├── libraries/ │ │ ├── test-macros/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ └── test-types/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── tools/ │ └── translation_table_tool/ │ ├── arch.rb │ ├── bsp.rb │ ├── generic.rb │ ├── kernel_elf.rb │ └── main.rb ├── 16_virtual_mem_part4_higher_half_kernel/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── kernel_virt_addr_space_size.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── null_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ ├── mapping_record.rs │ │ │ │ │ ├── page_alloc.rs │ │ │ │ │ ├── translation_table.rs │ │ │ │ │ └── types.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ ├── libraries/ │ │ ├── test-macros/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ └── test-types/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── tools/ │ └── translation_table_tool/ │ ├── arch.rb │ ├── bsp.rb │ ├── generic.rb │ ├── kernel_elf.rb │ └── main.rb ├── 17_kernel_symbols/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── kernel_virt_addr_space_size.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── null_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ ├── mapping_record.rs │ │ │ │ │ ├── page_alloc.rs │ │ │ │ │ ├── translation_table.rs │ │ │ │ │ └── types.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── symbols.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ ├── kernel_symbols/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── kernel_symbols.ld │ │ └── src/ │ │ └── main.rs │ ├── kernel_symbols.mk │ ├── libraries/ │ │ ├── debug-symbol-types/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ ├── test-macros/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ └── test-types/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── tools/ │ ├── kernel_symbols_tool/ │ │ ├── cmds.rb │ │ ├── kernel_elf.rb │ │ └── main.rb │ └── translation_table_tool/ │ ├── arch.rb │ ├── bsp.rb │ ├── generic.rb │ ├── kernel_elf.rb │ └── main.rb ├── 18_backtrace/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── backtrace.rs │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── backtrace.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── kernel_virt_addr_space_size.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── null_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── mmu/ │ │ │ │ │ ├── mapping_record.rs │ │ │ │ │ ├── page_alloc.rs │ │ │ │ │ ├── translation_table.rs │ │ │ │ │ └── types.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── symbols.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── 05_backtrace_sanity.rb │ │ ├── 05_backtrace_sanity.rs │ │ ├── 06_backtrace_invalid_frame.rb │ │ ├── 06_backtrace_invalid_frame.rs │ │ ├── 07_backtrace_invalid_link.rb │ │ ├── 07_backtrace_invalid_link.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ ├── kernel_symbols/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── kernel_symbols.ld │ │ └── src/ │ │ └── main.rs │ ├── kernel_symbols.mk │ ├── libraries/ │ │ ├── debug-symbol-types/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ ├── test-macros/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ └── test-types/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── tools/ │ ├── kernel_symbols_tool/ │ │ ├── cmds.rb │ │ ├── kernel_elf.rb │ │ └── main.rb │ └── translation_table_tool/ │ ├── arch.rb │ ├── bsp.rb │ ├── generic.rb │ ├── kernel_elf.rb │ └── main.rb ├── 19_kernel_heap/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── backtrace.rs │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── backtrace.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── kernel_virt_addr_space_size.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── buffer_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── heap_alloc.rs │ │ │ │ ├── mmu/ │ │ │ │ │ ├── mapping_record.rs │ │ │ │ │ ├── page_alloc.rs │ │ │ │ │ ├── translation_table.rs │ │ │ │ │ └── types.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── symbols.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── 05_backtrace_sanity.rb │ │ ├── 05_backtrace_sanity.rs │ │ ├── 06_backtrace_invalid_frame.rb │ │ ├── 06_backtrace_invalid_frame.rs │ │ ├── 07_backtrace_invalid_link.rb │ │ ├── 07_backtrace_invalid_link.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ ├── kernel_symbols/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── kernel_symbols.ld │ │ └── src/ │ │ └── main.rs │ ├── kernel_symbols.mk │ ├── libraries/ │ │ ├── debug-symbol-types/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ ├── test-macros/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ └── test-types/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── tools/ │ ├── kernel_symbols_tool/ │ │ ├── cmds.rb │ │ ├── kernel_elf.rb │ │ └── main.rb │ └── translation_table_tool/ │ ├── arch.rb │ ├── bsp.rb │ ├── generic.rb │ ├── kernel_elf.rb │ └── main.rb ├── 20_timer_callbacks/ │ ├── .cargo/ │ │ └── config.toml │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── kernel/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── src/ │ │ │ ├── _arch/ │ │ │ │ └── aarch64/ │ │ │ │ ├── backtrace.rs │ │ │ │ ├── cpu/ │ │ │ │ │ ├── boot.rs │ │ │ │ │ ├── boot.s │ │ │ │ │ └── smp.rs │ │ │ │ ├── cpu.rs │ │ │ │ ├── exception/ │ │ │ │ │ └── asynchronous.rs │ │ │ │ ├── exception.rs │ │ │ │ ├── exception.s │ │ │ │ ├── memory/ │ │ │ │ │ ├── mmu/ │ │ │ │ │ │ └── translation_table.rs │ │ │ │ │ └── mmu.rs │ │ │ │ └── time.rs │ │ │ ├── backtrace.rs │ │ │ ├── bsp/ │ │ │ │ ├── device_driver/ │ │ │ │ │ ├── arm/ │ │ │ │ │ │ ├── gicv2/ │ │ │ │ │ │ │ ├── gicc.rs │ │ │ │ │ │ │ └── gicd.rs │ │ │ │ │ │ └── gicv2.rs │ │ │ │ │ ├── arm.rs │ │ │ │ │ ├── bcm/ │ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller/ │ │ │ │ │ │ │ ├── local_ic.rs │ │ │ │ │ │ │ └── peripheral_ic.rs │ │ │ │ │ │ ├── bcm2xxx_interrupt_controller.rs │ │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ │ ├── bcm.rs │ │ │ │ │ └── common.rs │ │ │ │ ├── device_driver.rs │ │ │ │ ├── raspberrypi/ │ │ │ │ │ ├── cpu.rs │ │ │ │ │ ├── driver.rs │ │ │ │ │ ├── exception/ │ │ │ │ │ │ └── asynchronous.rs │ │ │ │ │ ├── exception.rs │ │ │ │ │ ├── kernel.ld │ │ │ │ │ ├── kernel_virt_addr_space_size.ld │ │ │ │ │ ├── memory/ │ │ │ │ │ │ └── mmu.rs │ │ │ │ │ └── memory.rs │ │ │ │ └── raspberrypi.rs │ │ │ ├── bsp.rs │ │ │ ├── common.rs │ │ │ ├── console/ │ │ │ │ └── buffer_console.rs │ │ │ ├── console.rs │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── smp.rs │ │ │ ├── cpu.rs │ │ │ ├── driver.rs │ │ │ ├── exception/ │ │ │ │ ├── asynchronous/ │ │ │ │ │ └── null_irq_manager.rs │ │ │ │ └── asynchronous.rs │ │ │ ├── exception.rs │ │ │ ├── lib.rs │ │ │ ├── main.rs │ │ │ ├── memory/ │ │ │ │ ├── heap_alloc.rs │ │ │ │ ├── mmu/ │ │ │ │ │ ├── mapping_record.rs │ │ │ │ │ ├── page_alloc.rs │ │ │ │ │ ├── translation_table.rs │ │ │ │ │ └── types.rs │ │ │ │ └── mmu.rs │ │ │ ├── memory.rs │ │ │ ├── panic_wait.rs │ │ │ ├── print.rs │ │ │ ├── state.rs │ │ │ ├── symbols.rs │ │ │ ├── synchronization.rs │ │ │ └── time.rs │ │ └── tests/ │ │ ├── 00_console_sanity.rb │ │ ├── 00_console_sanity.rs │ │ ├── 01_timer_sanity.rs │ │ ├── 02_exception_sync_page_fault.rs │ │ ├── 03_exception_restore_sanity.rb │ │ ├── 03_exception_restore_sanity.rs │ │ ├── 04_exception_irq_sanity.rs │ │ ├── 05_backtrace_sanity.rb │ │ ├── 05_backtrace_sanity.rs │ │ ├── 06_backtrace_invalid_frame.rb │ │ ├── 06_backtrace_invalid_frame.rs │ │ ├── 07_backtrace_invalid_link.rb │ │ ├── 07_backtrace_invalid_link.rs │ │ ├── boot_test_string.rb │ │ ├── panic_exit_success/ │ │ │ └── mod.rs │ │ └── panic_wait_forever/ │ │ └── mod.rs │ ├── kernel_symbols/ │ │ ├── Cargo.toml │ │ ├── build.rs │ │ ├── kernel_symbols.ld │ │ └── src/ │ │ └── main.rs │ ├── kernel_symbols.mk │ ├── libraries/ │ │ ├── debug-symbol-types/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ ├── test-macros/ │ │ │ ├── Cargo.toml │ │ │ └── src/ │ │ │ └── lib.rs │ │ └── test-types/ │ │ ├── Cargo.toml │ │ └── src/ │ │ └── lib.rs │ └── tools/ │ ├── kernel_symbols_tool/ │ │ ├── cmds.rb │ │ ├── kernel_elf.rb │ │ └── main.rb │ └── translation_table_tool/ │ ├── arch.rb │ ├── bsp.rb │ ├── generic.rb │ ├── kernel_elf.rb │ └── main.rb ├── Gemfile ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.CN.md ├── README.ES.md ├── README.md ├── SPONSORING.md ├── X1_JTAG_boot/ │ ├── .vscode/ │ │ └── settings.json │ ├── Cargo.toml │ ├── Makefile │ ├── README.md │ ├── build.rs │ ├── jtag_boot_rpi3.img │ ├── jtag_boot_rpi4.img │ ├── src/ │ │ ├── _arch/ │ │ │ └── aarch64/ │ │ │ ├── cpu/ │ │ │ │ ├── boot.rs │ │ │ │ └── boot.s │ │ │ ├── cpu.rs │ │ │ └── time.rs │ │ ├── bsp/ │ │ │ ├── device_driver/ │ │ │ │ ├── bcm/ │ │ │ │ │ ├── bcm2xxx_gpio.rs │ │ │ │ │ └── bcm2xxx_pl011_uart.rs │ │ │ │ ├── bcm.rs │ │ │ │ └── common.rs │ │ │ ├── device_driver.rs │ │ │ ├── raspberrypi/ │ │ │ │ ├── cpu.rs │ │ │ │ ├── driver.rs │ │ │ │ ├── kernel.ld │ │ │ │ └── memory.rs │ │ │ └── raspberrypi.rs │ │ ├── bsp.rs │ │ ├── console/ │ │ │ └── null_console.rs │ │ ├── console.rs │ │ ├── cpu/ │ │ │ └── boot.rs │ │ ├── cpu.rs │ │ ├── driver.rs │ │ ├── main.rs │ │ ├── panic_wait.rs │ │ ├── print.rs │ │ ├── synchronization.rs │ │ └── time.rs │ ├── tests/ │ │ └── boot_test_string.rb │ └── update.sh ├── common/ │ ├── docker.mk │ ├── format.mk │ ├── operating_system.mk │ ├── serial/ │ │ ├── minipush/ │ │ │ └── progressbar_patch.rb │ │ ├── minipush.rb │ │ └── miniterm.rb │ └── tests/ │ ├── boot_test.rb │ ├── console_io_test.rb │ ├── dispatch.rb │ ├── exit_code_test.rb │ └── test.rb ├── contributor_setup.sh ├── devtool_completion.bash ├── doc/ │ ├── 09_wiring_jtag.fzz │ ├── 09_wiring_jtag.xcf │ ├── 14_BCM_driver.drawio │ ├── 14_GICv2_driver.drawio │ ├── 14_header.drawio │ ├── demo_PS1.txt │ ├── source_section_divider.txt │ └── wiring.fzz ├── docker/ │ ├── README.md │ └── rustembedded-osdev-utils/ │ ├── Dockerfile │ ├── Makefile │ ├── auto │ ├── rpi3.cfg │ └── rpi4.cfg ├── rust-toolchain.toml └── utils/ ├── devtool/ │ └── copyright.rb ├── devtool.rb ├── diff_tut_folders.bash └── update_copyright.rb ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # editorconfig.org root = true [*] charset = utf-8 end_of_line = lf insert_final_newline = true indent_style = space trim_trailing_whitespace = true max_line_length = 100 [Dockerfile] indent_size = 4 [{Makefile,*.mk}] indent_style = tab indent_size = 8 [*.rb] indent_size = 4 [*.rs] indent_size = 4 [*.s] indent_style = tab indent_size = 8 [*.sh] indent_size = 4 [*.toml] indent_size = 4 [*.{yml,yaml}] indent_size = 2 ================================================ FILE: .githooks/pre-commit ================================================ #!/usr/bin/env ruby # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2018-2023 Andre Richter require_relative '../utils/devtool/copyright' def copyright_check(staged_files) source_files_exts = ['.S', '.rs', '.rb'] staged_files = staged_files.select do |f| next if f.include?('build.rs') next if f.include?('boot_test_string.rb') f.include?('Makefile') || f.include?('Dockerfile') || source_files_exts.include?(File.extname(f)) end return true if staged_files.empty? 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 # Copyright must be fixed manually. exit(1) unless copyright_check(staged_files) # Brute-force format. Don't care if it affects non-staged files as well, since we only add back the # staged ones. Dir.chdir(root_dir) { system('ruby utils/devtool.rb fmt') } staged_files.each { |f| system("git add #{f}") } exit(0) ================================================ FILE: .github/FUNDING.yml ================================================ custom: ["https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/blob/master/SPONSORING.md"] ================================================ FILE: .github/pull_request_template.md ================================================ ### Description Related Issue: ### Pre-commit steps - [ ] Tested on QEMU and real HW Rasperry Pi. - Not needed if it is just a README change or similar. - [ ] Ran `./contributor_setup.sh` followed by `./devtool ready_for_publish` - You'll need `Ruby` with `Bundler` and `NPM` installed locally. - If no Rust-related files were changed, `./devtool ready_for_publish_no_rust` can be used instead (faster). - This step is optional, but much appreciated if done. ================================================ FILE: .github/workflows/build_rpi3.yml ================================================ 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 * * *" jobs: build: name: Build kernels runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 - name: Set up Rust nightly run: | cargo install cargo-binutils 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 ================================================ FILE: .github/workflows/build_rpi4.yml ================================================ 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 * * *" jobs: build: name: Build kernels runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 - name: Set up Rust nightly run: | cargo install cargo-binutils 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 ================================================ FILE: .github/workflows/sanity.yml ================================================ name: Various Sanity Checks on: push: branches: - master pull_request: branches: - master jobs: build: name: Various Sanity Checks runs-on: ubuntu-22.04 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 ================================================ FILE: .github/workflows/test_integration.yml ================================================ 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 * * *" jobs: build: name: Run integration tests runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 - name: Set up Rust nightly run: | cargo install cargo-binutils 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 ================================================ FILE: .github/workflows/test_unit.yml ================================================ 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 * * *" jobs: build: name: Run boot and unit tests runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 - name: Set up Rust nightly run: | cargo install cargo-binutils 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 ================================================ FILE: .github/workflows/test_xtra.yml ================================================ name: Xtra-Tests on: push: branches: - master paths-ignore: - "utils/**" - "doc/**" - "docker/**" pull_request: branches: - master paths-ignore: - "utils/**" - "doc/**" - "docker/**" schedule: - cron: "0 5 * * *" jobs: build: name: Run xtra tests runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v3 - name: Set up Ruby uses: ruby/setup-ruby@v1 - name: Set up Rust nightly run: | cargo install cargo-binutils - name: Set up Ruby run: | gem install bundler bundle config set without 'uart' bundle install --retry 3 - name: Run run: | bundle exec ruby utils/devtool.rb make_xtra ================================================ FILE: .gitignore ================================================ **/target/* **/.gdb_history **/kernel8.img node_modules .bundle .vendor Gemfile.lock package*.json ================================================ FILE: .prettierignore ================================================ **/* !**/*/ **/target/ node_modules/ .vendor/ !*.json !*.yml ================================================ FILE: .prettierrc.json ================================================ { "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" } } ] } ================================================ FILE: .rubocop.yml ================================================ # The behavior of RuboCop can be controlled via the .rubocop.yml # configuration file. It makes it possible to enable/disable # certain cops (checks) and to alter their behavior if they accept # any parameters. The file can be placed either in your home # directory or in some project directory. # # RuboCop will start looking for the configuration file in the directory # where the inspected file is and continue its way up to the root directory. # # See https://github.com/rubocop-hq/rubocop/blob/master/manual/configuration.md Layout/IndentationWidth: Width: 4 AllowedPatterns: ['^\s*module'] Layout/LineLength: Max: 100 Lint/UnusedMethodArgument: AutoCorrect: False Metrics/AbcSize: Max: 25 Metrics/ClassLength: Enabled: false Metrics/MethodLength: Max: 20 AllCops: NewCops: enable ================================================ FILE: .ruby-version ================================================ 3.0.2 ================================================ FILE: .rustfmt.toml ================================================ newline_style = "Unix" edition = "2021" imports_granularity = "Crate" format_code_in_doc_comments = true normalize_comments = true wrap_comments = true comment_width = 100 ================================================ FILE: .vscode/settings.json ================================================ { "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 } ================================================ FILE: 00_before_we_start/README.CN.md ================================================ # 在我们开始之前 下面的文本内容是1:1 复制的文档。在每个教程的内核主要源代码文档的头部。它描述了源代码的主要结构并且试着去传达各个方法背后的理念。请阅读文章以便你能熟悉你在教程中将会遇到的东西。这将帮助你更好的浏览代码和理解不同章节的区别和增量内容。 另请注意,以下文字将引用源代码文件(例如`**/memory.rs`)或在本教程的第一批教程中尚不存在的功能。 它们将被逐渐添加到本教程。 玩的开心! ## 代码组织和结构 代码被划分成不同的*模块*,每个模块代表一个内核典型的子系统。子系统的顶层模块文件直接位于`src`文件夹中。例如,`src/memory.rs`这个包含了所有与内存管理有关的代码。 ## 处理器架构代码的可见性 有的内核的子系统是基于特定目标架构的处理器的低级代码。对于每种支持的处理器架构,都有一个子文件夹在`src/_arch`中。例如,`src/_arch/aarch64` 子模块系统在每个处理器架构的`src`文件夹中。例如,属于内核内存子系统(`src/memory.rs`)的代码将会被放在`src/_arch/aarch64/memory.rs`.后一个文件将被直接包含和重新导出到`src/memory.rs`中,以便架构代码部分是明显的遵循代码模块化。这意味着在`src/_arch/aarch64/memory.rs`中定义的公共函数foo()。仅可通过`crate :: memory :: foo()`访问。 `_arch`中的`_`表示此文件夹不属于标准模块层次结构。而是使用`#[path =“ _ arch/xxx/yyy.rs”]`属性将其内容有条件地引入各自的文件中。 ## BSP 代码 `BSP` 表示 Board Support Package。`BSP`代码在`src/bsp.rs`中,而且包含目标主板特殊的定义和功能。这些是诸如主板的内存映射或相应主板上的设备驱动程序实例之类的东西。 就像处理器架构代码一样,`BSP`代码模块架构也是试着镜像`kernel`的子系统模块,但是这次它没有明显地包含和重新导出。这意味着必须从bsp名称空间开始调用提供的所有内容,例如,`bsp::driver::driver_manager()`。 ## 内核接口 `arch`和`bsp`都包含根据实际目标和主板不同而编译的代码。例如,`interrupt controller`对于硬件`Raspberry Pi 3`和`Raspberry Pi 4`是不同的,但是我们想让`kernel`剩下的代码可以轻松地适配它们。 为了在`arch`,`bsp`和`generic kernel code`之间提供一个清晰的抽象,`interface`特征在*在可能的情况下*和*在可能的地方*被提供。它们在各自的子系统模块中定义,并有助于将程序的调用方法体现到接口,而不是具体实现上。例如,有一个通用IRQ处理接口,由两个树莓派不同的中断控制器驱动将实现的,并且仅将接口导出到`kernel`剩下的代码中。 ``` +-------------------+ | Interface (Trait) | | | +--+-------------+--+ ^ ^ | | | | +----------+--+ +--+----------+ | kernel code | | bsp code | | | | arch code | +-------------+ +-------------+ ``` # 总结 对于一个逻辑`kernel`子系统,相应的代码可以分布在几个物理位置。这里有个内存子系统的例子: - `src/memory.rs` and `src/memory/**/*` - 与目标处理器体系结构和“BSP”特性无关的通用代码。 - 例如: 将大块内存归零的函数 - 通过`arch`和`BSP`代码实现的内存子系统接口。 - 例如: 一个`MMU`接口定义的`MMU`功能原型 - `src/bsp/__board_name__/memory.rs` 和 `src/bsp/__board_name__/memory/**/*` - `BSP` 具体代码. - 例如: 主板内存映射 (DRAM物理地址 和 MMIO 设备). - `src/_arch/__arch_name__/memory.rs` 和 `src/_arch/__arch_name__/memory/**/*` - 处理器架构的具体代码。 - 例如:为`__arch_name__` 处理器架构实现的`MMU`接口。 从一个命名空间角度来看,内存子系统代码在: - `crate::memory::*` - `crate::bsp::memory::*` ================================================ FILE: 00_before_we_start/README.ES.md ================================================ # Antes de comenzar El texto a continuación es una copia 1:1 de la documentación que puede ser encontrada al principio del archivo del código fuente del núcleo (kernel) en cada tutorial. Esta describe la estructura general del código fuente, e intenta transmitir la filosofía detrás de cada enfoque. Por favor leélo para familiarizarte con lo que te vas a encontrar durante los tutoriales. Te ayudará a navegar el código de una mejor manera y a entender las diferencias y agregados entre los diferentes tutoriales. Por favor, nota también que el siguiente texto va a referenciar los archivos del código fuente (p. e.j. `**/memory.rs`) o funciones que no van a existir aún en los primeros tutoriales. Estos archivos serán agregados a medida que el tutorial avance. ¡Diviértanse! # La estructura del código y la arquitectura El código está dividido en diferentes módulos donde cada uno representa un subsistema típico del `kernel (núcleo)`. Los módulos de más alto nivel de los subsistemas se encuentran directamente en la carpeta `src`. Por ejemplo, `src/memory.rs` contiene el código que está relacionado con el manejo de memoria. ## Visibilidad del código de arquitectura del procesador Algunos de los subsistemas del `núcleo (kernel)` dependen del código de bajo nivel (low-level) dedicado a la arquitectura del procesador. Por cada arquitectura de procesador que está soportada, existe una subcarpeta en `src/_arch`, por ejemplo, `src/_arch/aarch64`. La carpeta de arquitecturas refleja los módulos del subsistema establecidos en `src`. Por ejemplo, el código de arquitectura que pertenece al subsistema MMU del `núcleo(kernel)` (`src/memory/mmu.rs`) irá dentro de (`src/_arch/aarch64/memory/mmu.rs`). Este archivo puede ser cargado como un módulo en `src/memory/mmu.rs` usando el `path attribute` (atributo de ruta). Usualmente, el nombre del módulo elegido es el nombre del módulo genérico con el prefijo de `arch_` Por ejemplo, esta es la parte superior de `src/memory/mmu.rs`: ``` #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; ``` En muchas ocasiones, los elementos de `arch_module` serán reexportados públicamente por el módulo principal. De esta manera, cada módulo específico de la arquitectura puede proporcionar su implementación de un elemento, mientras que el *invocante* no debe de preocuparse por la arquitectura que se ha compilado condicionalmente. ## Código BSP `BSP` significa Board Support Package (Paquete de Soporte de la Placa). El código `BSP` está dentro de `src/bsp.rs` y contiene las definiciones y funciones de la placa base específica elegida. Entre estas cosas se encuentran diferentes elementos como el mapa de memoria de la placa o instancias de controladores para dispositivos que se presentan en la placa elegida. Justo como el código de la arquitectura del procesador, la estructura del módulo del código `BSP` trata de reflejar los módulos del subsistema del `núcleo (kernel)`, pero no ocurre una reexportación esta vez. Eso significa que lo que sea que se esté proporcionando debe ser llamado empezando por el *namespace* (espacio de nombres) de `bsp`, p. ej. `bsp::driver::driver_manager()`. ## La interfaz del núcleo (kernel) El `arch` y el `bsp` contienen código que se compilará condicionalmente dependiendo del procesador y placa actual para la que se compila el núcleo (kernel). Por ejemplo, el hardware de control de interrupciones de la `Raspberry Pi 3` y la `Raspberry Pi 4` es diferente, pero nosotros queremos que el resto del código del kernel funcione correctamente con cualquiera de los dos sin mucha complicación. Para poder dar una limpia abstracción entre `arch`, `bsp` y código genérico del núcleo, los rasgos de `interface` se proporcionan *siempre y cuando tenga sentido*. Son definidos en su módulo de subsistema correspondiente y ayuda a reforzar el patrón de programar con respecto a una interfaz, sin importar la implementación concreta. Por ejemplo, habrá una *IRQ handling interface* (interfaz de manejo de interrupciones) común, el cual los dos diferentes controladores de ambas `Raspberry` implementarán, y solo exportarán la interfaz común al resto del `núcleo (kernel)`. ``` +-------------------+ | Interface (Trait) | | | +--+-------------+--+ ^ ^ | | | | +----------+--+ +--+----------+ | kernel code | | bsp code | | | | arch code | +-------------+ +-------------+ ``` # Resumen Para un subsistema lógico del `núcleo (kernel)`, el código correspondiente puede ser distribuido sobre diferentes localizaciones físicas. Aquí un ejemplo para el subsistema de memoria: - `src/memory.rs` y `src/memory/**/*` - Código común que es independiente de la arquitectura del procesador de destino y las características de la placa (`BSP`). - Ejemplo: Una función para poner a cero un trozo de memoria. - Las interfaces para el subsistema de la memoria que son implementados por código de `arch` o `BSP`. - Ejemplo: Una interfaz `MMU` que define prototipos de función de `MMU`. - `src/bsp/__board_name__/memory.rs` y `src/bsp/__board_name__/memory/**/*` - Código específico de `BSP`. - Ejemplo: El mapa de memoria de la placa (direcciones físicas de DRAM y dispositivos MMIO). - `src/_arch/__arch_name__/memory.rs` y `src/_arch/__arch_name__/memory/**/*` - El código específico de la arquitectura del procesador. - Ejemplo: Implementación de la interfaz `MMU` para la arquitectura `__arch_name__`. Desde una perspectiva de *namespace*, el código del subsistema de **memoria** vive en: - `crate::memory::*` - `crate::bsp::memory::*` # Flujo de Boot / Boot flow 1. El punto de entrada del núcleo (kernel) es la función `cpu::boot::arch_boot::_start()`. - Está implementado en `src/_arch/__arch_name__/cpu/boot.s`. ================================================ FILE: 00_before_we_start/README.md ================================================ # Before we start The following text is a 1:1 copy of the documentation that can be found at the top of the kernel's main source code file in each tutorial. It describes the general structure of the source code, and tries to convey the philosophy behind the respective approach. Please read it to make yourself familiar with what you will encounter during the tutorials. It will help you to navigate the code better and understand the differences and additions between the separate tutorials. Please also note that the following text will reference source code files (e.g. `**/memory.rs`) or functions that won't exist yet in the first bunch of the tutorials. They will be added gradually as the tutorials advance. Have fun! # 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`. ================================================ FILE: 01_wait_forever/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 01_wait_forever/Cargo.toml ================================================ [package] name = "mingo" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = [] bsp_rpi4 = [] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] ================================================ FILE: 01_wait_forever/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ================================================ FILE: 01_wait_forever/README.CN.md ================================================ # 教程 01 - 一直等待(死循环) ## tl;dr 项目框架已经构建完成;目前代码做的仅仅是挂起CPU核心执行内核代码。 - `Makefile` 目标项: - `doc`: 生成文档。 - `qemu`: 在 QEMU 中运行 `kernel`。 - `clippy` - `clean` - `readelf`: 检查 `ELF` 输出。 - `objdump`: 检查汇编。 - `nm`: 检查符号。 - 代码按照 `kernel`, `arch` 和 `BSP` (板级支持包)的形式组织。 - 条件编译会根据用户提供的参数编译各自的 `arch` 和 `BSP` 的内容。 - 自定义 `kernel.ld` 链接脚本. - 载入地址为 `0x80_000` - 目前仅有 `.text` 小节(section)。 - `main.rs`: 重要的 [inner attributes]: - `#![no_std]`, `#![no_main]` - 汇编函数 `_start()` 会执行 `wfe` (Wait For Event), 并挂起所有正在执行 `_start()` 的核心。 - 我们(必须)定义一个 `#[panic_handler]` 函数。 - 用于等待cpu事件的发生。 [inner attributes]: https://doc.rust-lang.org/reference/attributes.html ### 测试一下! 在项目文件夹下调用 QEMU 并观察在 `wfe` 中CPU核心的运转情况: ```console » make qemu [...] IN: 0x00080000: d503205f wfe 0x00080004: 17ffffff b #0x80000 ``` ================================================ FILE: 01_wait_forever/README.ES.md ================================================ # Tutorial 01 - Esperar infinitamente ## tl;dr * Se configura la estructura que tiene el proyecto. * Se ejecuta una pequeño código hecho en ensamblador que tiene como función detener todos los núcleos del procesador que están ejecutando el kernel. ## Compilar * El archivo `Makefile` permite ejecutar: * `doc`: Genera la documentación. * `qemu`: Ejecutar el kernel en QEMU. * `clippy`: Analiza el código y sugiere mejoras. * `clean`: Elimina todos los archivos generados durante la compilación, etc. * `readelf`: Inspecciona el archivo `ELF` de salida. * `objdump`: Inspecciona el ensamblador. * `nm`: Inspecciona los símbolos. ## Código a revisar * El script para enlazado específico para la `BSP` llamado `kernel.ld`. * Carga la dirección en `0x8_0000`. * Solo la sección `.text`. * `main.rs`: [Atributos internos](https://doc.rust-lang.org/reference/attributes.html) importantes: * `#![no_std]`, `#![no_main]`. * `boot.s`: La función de ensamblador `_start()` que inicia `wfe` (Wait For Event / Esperar Hasta Un Evento), detiene todos los núcleos del procesador que están ejecutando `_start()`. * Tenemos que definir una función que funcione como `#[panic_handler]` (manejador de pánico) para que el compilador no nos cause problemas. * Hazla `unimplemented!()` porque se eliminará ya que no está siendo usada. ## Pruébalo Dentro de la carpeta del proyecto, ejecuta a QEMU y mira el núcleo del procesador ejecutando `wfe` en bucle: ``` $ make qemu [...] IN: 0x00080000: d503205f wfe 0x00080004: 17ffffff b #0x80000 ``` ================================================ FILE: 01_wait_forever/README.md ================================================ # Tutorial 01 - Wait Forever ## tl;dr - The project skeleton is set up. - A small piece of assembly code runs that just halts all CPU cores executing the kernel code. ## Building - `Makefile` targets: - `doc`: Generate documentation. - `qemu`: Run the `kernel` in QEMU - `clippy` - `clean` - `readelf`: Inspect the `ELF` output. - `objdump`: Inspect the assembly. - `nm`: Inspect the symbols. ## Code to look at - `BSP`-specific `kernel.ld` linker script. - Load address at `0x8_0000` - Only `.text` section. - `main.rs`: Important [inner attributes]: - `#![no_std]`, `#![no_main]` - `boot.s`: Assembly `_start()` function that executes `wfe` (Wait For Event), halting all cores that are executing `_start()`. - We (have to) define a `#[panic_handler]` function to make the compiler happy. - Make it `unimplemented!()` because it will be stripped out since it is not used. [inner attributes]: https://doc.rust-lang.org/reference/attributes.html ### Test it In the project folder, invoke QEMU and observe the CPU core spinning on `wfe`: ```console $ make qemu [...] IN: 0x00080000: d503205f wfe 0x00080004: 17ffffff b #0x80000 ``` ================================================ FILE: 01_wait_forever/build.rs ================================================ 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())); } ================================================ FILE: 01_wait_forever/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!(include_str!("boot.s")); ================================================ FILE: 01_wait_forever/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 01_wait_forever/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW */ PHDRS { segment_code PT_LOAD FLAGS(5); } SECTIONS { . = __rpi_phys_binary_load_addr; /*********************************************************************************************** * Code ***********************************************************************************************/ .text : { KEEP(*(.text._start)) } :segment_code } ================================================ FILE: 01_wait_forever/src/bsp/raspberrypi.rs ================================================ // 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. // Coming soon. ================================================ FILE: 01_wait_forever/src/bsp.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use raspberrypi::*; ================================================ FILE: 01_wait_forever/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 01_wait_forever/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. mod boot; ================================================ FILE: 01_wait_forever/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. #![no_main] #![no_std] mod bsp; mod cpu; mod panic_wait; // Kernel code coming next tutorial. ================================================ FILE: 01_wait_forever/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- #[panic_handler] fn panic(_info: &PanicInfo) -> ! { unimplemented!() } ================================================ FILE: 02_runtime_init/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 02_runtime_init/Cargo.toml ================================================ [package] name = "mingo" version = "0.2.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = [] bsp_rpi4 = [] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 02_runtime_init/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -d in_asm -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ================================================ FILE: 02_runtime_init/README.CN.md ================================================ # 教程 02 - 执行初始化 ## tl;dr - 我们拓展了`boot.S`,在第一次启动的时候调用Rust代码。 在跳转到rust代码前,对运行时进行了一些初始化工作。 - Rust通过调用`panic()`挂起CPU。 - 再次运行`make qemu`看看新增加的代码是怎么运行的。 ## 值得注意的变化 - 链接脚本(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) 请检查[英文版本](README.md#diff-to-previous),这是最新的。 ================================================ FILE: 02_runtime_init/README.ES.md ================================================ # Tutorial 02 - Inicialización del `runtime` ## tl;dr * Extendimos la funcionalidad de `boot.s` para que sea capaz de llamar código Rust por primera vez. Antes de que el cambio a Rust ocurra, se realizan algunos trabajos de inicialización del `runtime` (soporte para ejecución de código). * El código Rust que es llamado solo pausa la ejecución con una llamada a `panic!()`. * Ejecuta `make qemu` de nuevo para que puedas ver el código adicional en acción. ## Adiciones importantes * Adiciones importantes al script `kernel.ld`: * Nuevas secciones: `.rodata`, `.got`, `.data`, `.bss`. * Un lugar totalmente dedicado a enlazar argumentos de tiempo de arranque (boot-time) que necesitan estar listos cuando se llame a `_start()`. * `_start()` en `_arch/__arch_name__/cpu/boot.s`: 1. Para todos los núcleos expecto el núcleo 0. 2. Inicializa la [`DRAM`](https://es.wikipedia.org/wiki/DRAM) poniendo a cero la sección [`.bss`](https://en.wikipedia.org/wiki/.bss). 3. Configura el `stack pointer` (puntero a la memoria [pila](https://es.wikipedia.org/wiki/Pila_(inform%C3%A1tica))). 4. Salta hacia la función `_start_rust()`, definida en `arch/__arch_name__/cpu/boot.rs`. * `_start_rust()`: * Llama a `kernel_init()`, que llama a `panic!()`, que al final también pone al núcleo 0 en pausa. * La librería ahora usa el crate [aarch64-cpu](https://github.com/rust-embedded/aarch64-cpu), que nos da abstracciones sin coste y envuelve las partes que hacen uso de un `unsafe` (partes con código que no es seguro y podría causar errores) cuando se trabaja directamente con los recursos del procesador. * Lo puedes ver en acción en `_arch/__arch_name__/cpu.rs`. ## Diferencia con el archivo anterior Please check [the english version](README.md#diff-to-previous), which is kept up-to-date. ================================================ FILE: 02_runtime_init/README.md ================================================ # Tutorial 02 - Runtime Init ## tl;dr - We extend `boot.s` to call into Rust code for the first time. Before the jump to Rust happens, a bit of runtime init work is done. - The Rust code being called just halts execution with a call to `panic!()`. - Check out `make qemu` again to see the additional code run. ## Notable additions - More additions to the linker script: - New sections: `.rodata`, `.got`, `.data`, `.bss`. - A dedicated place for linking boot-time arguments that need to be read by `_start()`. - `_start()` in `_arch/__arch_name__/cpu/boot.s`: 1. Halts core if core != core0. 1. Initializes the `DRAM` by zeroing the [bss] section. 1. Sets up the `stack pointer`. 1. Jumps to the `_start_rust()` function, defined in `arch/__arch_name__/cpu/boot.rs`. - `_start_rust()`: - Calls `kernel_init()`, which calls `panic!()`, which eventually halts core0 as well. - The library now uses the [aarch64-cpu] crate, which provides zero-overhead abstractions and wraps `unsafe` parts when dealing with the CPU's resources. - See it in action in `_arch/__arch_name__/cpu.rs`. [bss]: https://en.wikipedia.org/wiki/.bss [aarch64-cpu]: https://github.com/rust-embedded/aarch64-cpu ## Diff to previous ```diff diff -uNr 01_wait_forever/Cargo.toml 02_runtime_init/Cargo.toml --- 01_wait_forever/Cargo.toml +++ 02_runtime_init/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.1.0" +version = "0.2.0" authors = ["Andre Richter "] edition = "2021" @@ -21,3 +21,7 @@ ##-------------------------------------------------------------------------------------------------- [dependencies] + +# Platform specific dependencies +[target.'cfg(target_arch = "aarch64")'.dependencies] +aarch64-cpu = { version = "9.x.x" } diff -uNr 01_wait_forever/Makefile 02_runtime_init/Makefile --- 01_wait_forever/Makefile +++ 02_runtime_init/Makefile @@ -181,6 +181,7 @@ $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ + --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ diff -uNr 01_wait_forever/src/_arch/aarch64/cpu/boot.rs 02_runtime_init/src/_arch/aarch64/cpu/boot.rs --- 01_wait_forever/src/_arch/aarch64/cpu/boot.rs +++ 02_runtime_init/src/_arch/aarch64/cpu/boot.rs @@ -14,4 +14,19 @@ use core::arch::global_asm; // Assembly counterpart to this file. -global_asm!(include_str!("boot.s")); +global_asm!( + include_str!("boot.s"), + CONST_CORE_ID_MASK = const 0b11 +); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The Rust entry of the `kernel` binary. +/// +/// The function is called from the assembly `_start` function. +#[no_mangle] +pub unsafe fn _start_rust() -> ! { + crate::kernel_init() +} diff -uNr 01_wait_forever/src/_arch/aarch64/cpu/boot.s 02_runtime_init/src/_arch/aarch64/cpu/boot.s --- 01_wait_forever/src/_arch/aarch64/cpu/boot.s +++ 02_runtime_init/src/_arch/aarch64/cpu/boot.s @@ -3,6 +3,22 @@ // Copyright (c) 2021-2023 Andre Richter //-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +// Load the address of a symbol into a register, PC-relative. +// +// The symbol must lie within +/- 4 GiB of the Program Counter. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_REL register, symbol + adrp \register, \symbol + add \register, \register, #:lo12:\symbol +.endm + +//-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start @@ -11,6 +27,34 @@ // fn _start() //------------------------------------------------------------------------------ _start: + // Only proceed on the boot core. Park it otherwise. + mrs x0, MPIDR_EL1 + and x0, x0, {CONST_CORE_ID_MASK} + ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x0, x1 + b.ne .L_parking_loop + + // If execution reaches here, it is the boot core. + + // Initialize DRAM. + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive + +.L_bss_init_loop: + cmp x0, x1 + b.eq .L_prepare_rust + stp xzr, xzr, [x0], #16 + b .L_bss_init_loop + + // Prepare the jump to Rust code. +.L_prepare_rust: + // Set the stack pointer. + ADR_REL x0, __boot_core_stack_end_exclusive + mov sp, x0 + + // Jump to Rust code. + b _start_rust + // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe 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-2023 Andre Richter + +//! Architectural processor code. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::arch_cpu + +use aarch64_cpu::asm; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Pause execution on the core. +#[inline(always)] +pub fn wait_forever() -> ! { + loop { + asm::wfe() + } +} diff -uNr 01_wait_forever/src/bsp/raspberrypi/cpu.rs 02_runtime_init/src/bsp/raspberrypi/cpu.rs --- 01_wait_forever/src/bsp/raspberrypi/cpu.rs +++ 02_runtime_init/src/bsp/raspberrypi/cpu.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Processor code. + +//-------------------------------------------------------------------------------------------------- +// Public 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/kernel.ld 02_runtime_init/src/bsp/raspberrypi/kernel.ld --- 01_wait_forever/src/bsp/raspberrypi/kernel.ld +++ 02_runtime_init/src/bsp/raspberrypi/kernel.ld @@ -3,6 +3,8 @@ * Copyright (c) 2018-2023 Andre Richter */ +__rpi_phys_dram_start_addr = 0; + /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; @@ -13,21 +15,65 @@ * 4 == R * 5 == RX * 6 == RW + * + * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. + * It doesn't mean all of them need actually be loaded. */ PHDRS { - segment_code PT_LOAD FLAGS(5); + segment_boot_core_stack PT_LOAD FLAGS(6); + segment_code PT_LOAD FLAGS(5); + segment_data PT_LOAD FLAGS(6); } SECTIONS { - . = __rpi_phys_binary_load_addr; + . = __rpi_phys_dram_start_addr; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : + { + /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack /*********************************************************************************************** - * Code + * Code + RO Data + Global Offset Table ***********************************************************************************************/ .text : { KEEP(*(.text._start)) + *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ + *(.text._start_rust) /* The Rust entry point */ + *(.text*) /* Everything else */ } :segment_code + + .rodata : ALIGN(8) { *(.rodata*) } :segment_code + + /*********************************************************************************************** + * Data + BSS + ***********************************************************************************************/ + .data : { *(.data*) } :segment_data + + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ + .bss (NOLOAD) : ALIGN(16) + { + __bss_start = .; + *(.bss*); + . = ALIGN(16); + __bss_end_exclusive = .; + } :segment_data + + /*********************************************************************************************** + * Misc + ***********************************************************************************************/ + .got : { *(.got*) } + ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") + + /DISCARD/ : { *(.comment*) } } diff -uNr 01_wait_forever/src/bsp/raspberrypi.rs 02_runtime_init/src/bsp/raspberrypi.rs --- 01_wait_forever/src/bsp/raspberrypi.rs +++ 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 @@ -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] @@ -112,4 +114,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,6 +4,7 @@ //! A panic handler that infinitely waits. +use crate::cpu; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- @@ -12,5 +13,5 @@ #[panic_handler] fn panic(_info: &PanicInfo) -> ! { - unimplemented!() + cpu::wait_forever() } ``` ================================================ FILE: 02_runtime_init/build.rs ================================================ 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())); } ================================================ FILE: 02_runtime_init/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: 02_runtime_init/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x0, MPIDR_EL1 and x0, x0, {CONST_CORE_ID_MASK} ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x0, x1 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Jump to Rust code. b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 02_runtime_init/src/_arch/aarch64/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::arch_cpu use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { loop { asm::wfe() } } ================================================ FILE: 02_runtime_init/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 02_runtime_init/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 02_runtime_init/src/bsp/raspberrypi.rs ================================================ // 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; ================================================ FILE: 02_runtime_init/src/bsp.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use raspberrypi::*; ================================================ FILE: 02_runtime_init/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 02_runtime_init/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::wait_forever; ================================================ FILE: 02_runtime_init/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![feature(asm_const)] #![no_main] #![no_std] mod bsp; mod cpu; mod panic_wait; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { panic!() } ================================================ FILE: 02_runtime_init/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::cpu; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- #[panic_handler] fn panic(_info: &PanicInfo) -> ! { cpu::wait_forever() } ================================================ FILE: 03_hacky_hello_world/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 03_hacky_hello_world/Cargo.toml ================================================ [package] name = "mingo" version = "0.3.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = [] bsp_rpi4 = [] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 03_hacky_hello_world/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 03_hacky_hello_world/README.CN.md ================================================ # 教程 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),这是最新的。 ================================================ FILE: 03_hacky_hello_world/README.ES.md ================================================ # Tutorial 03 - Hacky Hello World ## tl;dr * Se añade la macro global `print!()` para habilitar la "depuración basada en printf" ("printf debugging") lo más pronto posible. * Para mantener una duración razonable en este tutorial, las funciones de impresión por el momento "abusan" una propiedad de QEMU que nos permite hacer uso del `UART` de la Raspberry sin haberla configurado apropiadamente. * El uso del hardware real de `UART` se habilitará paso por paso en los siguientes tutoriales. ## Adiciones notables * `src/console.rs` introduce una interfaz con `Trait`s para comandos de consola. * `src/bsp/raspberrypi/console.rs` implementa la interfaz para que QEMU pueda crear una emulación de UART. * El *panic handler* (manejador de pánico) hace uso de la nueva macro `print!()` para mostrar mensajes de error del usuario. * Hay un nuevo objetivo en el Makefile: `make test`, destinado a la automatización de pruebas. Este comando inicia el kernel (núcleo) compilado en `QEMU`, y busca una cadena de texto específica en la salida que ha sido producida por el kernel (núcleo). * En este tutorial, se buscará la cadena `Stopping here`, que es creada por la macro `panic!()` al final del archivo `main.rs`. ## Pruébalo QEMU ya no está siendo ejecutado en modo ensamblador. Desde ahora en adelante mostrará la salida de la `consola`. ```console $ make qemu [...] Hello from Rust! Kernel panic: Stopping here. ``` ### Diccionario * *Hacky:* Solución torpe o poco elegante para un problema. * *Debugging:* Proceso para identificar y corregir errores de programación. * *printf debugging:* Usado para describir el trabajo de depuración (*debugging*) poniendo comandos que dan una salida en consola, como el de "printf", en diferentes lugares del programa; observando la información y tratando de deducir qué está mal en el programa basándose en la información que nos dan nuestros comandos. * *Traits:* Un *trait* le hace saber al compilador de Rust acerca de una funcionalidad que tiene un tipo de dato particular y que puede compartir con otros tipos de datos. > NOTA: Los *traits* son similares a una característica que se le conoce comúnmente como *interfaces* en otros lenguajes, aunque con algunas diferencias. Si deseas aprender más acerca de esto, por favor lee este capítulo del libro de Rust: [Traits: Defining Shared Behavior - The Rust Programming Language](https://doc.rust-lang.org/book/ch10-02-traits.html) ## Diferencias con el archivo anterior Please check [the english version](README.md#diff-to-previous), which is kept up-to-date. ================================================ FILE: 03_hacky_hello_world/README.md ================================================ # Tutorial 03 - Hacky Hello World ## tl;dr - 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 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 `println!()` to display user error messages. - There is a new Makefile target, `make test`, intended for automated testing. It boots the compiled kernel in `QEMU`, and checks for an expected output string produced by the kernel. - In this tutorial, it checks for the string `Stopping here`, which is emitted by the `panic!()` at the end of `main.rs`. ## Test it QEMU is no longer running in assembly mode. It will from now on show the output of the `console`. ```console $ make qemu [...] Hello from Rust! Kernel panic! Panic location: File 'src/main.rs', line 126, column 5 Stopping here. ``` ## Diff to previous ```diff diff -uNr 02_runtime_init/Cargo.toml 03_hacky_hello_world/Cargo.toml --- 02_runtime_init/Cargo.toml +++ 03_hacky_hello_world/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.2.0" +version = "0.3.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 02_runtime_init/Makefile 03_hacky_hello_world/Makefile --- 02_runtime_init/Makefile +++ 03_hacky_hello_world/Makefile @@ -25,7 +25,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 @@ -36,7 +36,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 @@ -86,17 +86,20 @@ --strip-all \ -O binary -EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ -DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial -DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial +DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i +DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) +DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) @@ -191,3 +194,27 @@ $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt + + +##-------------------------------------------------------------------------------------------------- +## Testing targets +##-------------------------------------------------------------------------------------------------- +.PHONY: test test_boot + +ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. + +test_boot test: + $(call color_header, "$(QEMU_MISSING_STRING)") + +else # QEMU is supported. + +##------------------------------------------------------------------------------ +## Run boot test +##------------------------------------------------------------------------------ +test_boot: $(KERNEL_BIN) + $(call color_header, "Boot test - $(BSP)") + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + +test: test_boot + +endif diff -uNr 02_runtime_init/src/bsp/raspberrypi/console.rs 03_hacky_hello_world/src/bsp/raspberrypi/console.rs --- 02_runtime_init/src/bsp/raspberrypi/console.rs +++ 03_hacky_hello_world/src/bsp/raspberrypi/console.rs @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 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,32 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! System console. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Console interfaces. +pub mod interface { + /// 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; +} + +//-------------------------------------------------------------------------------------------------- +// 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 @@ -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] #![no_std] mod bsp; +mod console; mod cpu; mod panic_wait; +mod print; /// Early init code. /// @@ -120,5 +124,7 @@ /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { - panic!() + println!("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,14 +4,61 @@ //! A panic handler that infinitely waits. -use crate::cpu; +use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- +/// Stop immediately if called a second time. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store +fn panic_prevent_reenter() { + use core::sync::atomic::{AtomicBool, Ordering}; + + #[cfg(not(target_arch = "aarch64"))] + compile_error!("Add the target_arch to above's check if the following code is safe to use"); + + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + + return; + } + + cpu::wait_forever() +} + #[panic_handler] -fn panic(_info: &PanicInfo) -> ! { +fn panic(info: &PanicInfo) -> ! { + // Protect against panic infinite loops if any of the following code panics itself. + panic_prevent_reenter(); + + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "Kernel panic!\n\n\ + Panic location:\n File '{}', line {}, column {}\n\n\ + {}", + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + cpu::wait_forever() } diff -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-2023 Andre Richter + +//! Printing. + +use crate::console; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +#[doc(hidden)] +pub fn _print(args: fmt::Arguments) { + use console::interface::Write; + + 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' ``` ================================================ FILE: 03_hacky_hello_world/build.rs ================================================ 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())); } ================================================ FILE: 03_hacky_hello_world/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: 03_hacky_hello_world/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x0, MPIDR_EL1 and x0, x0, {CONST_CORE_ID_MASK} ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x0, x1 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Jump to Rust code. b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 03_hacky_hello_world/src/_arch/aarch64/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::arch_cpu use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { loop { asm::wfe() } } ================================================ FILE: 03_hacky_hello_world/src/bsp/raspberrypi/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 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 {} } ================================================ FILE: 03_hacky_hello_world/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 03_hacky_hello_world/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 03_hacky_hello_world/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod console; pub mod cpu; ================================================ FILE: 03_hacky_hello_world/src/bsp.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use raspberrypi::*; ================================================ FILE: 03_hacky_hello_world/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. use crate::bsp; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { /// 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; } //-------------------------------------------------------------------------------------------------- // 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() } ================================================ FILE: 03_hacky_hello_world/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 03_hacky_hello_world/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::wait_forever; ================================================ FILE: 03_hacky_hello_world/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod panic_wait; mod print; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { println!("Hello from Rust!"); panic!("Stopping here.") } ================================================ FILE: 03_hacky_hello_world/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 03_hacky_hello_world/src/print.rs ================================================ // 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) { use console::interface::Write; 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)*)); }) } ================================================ FILE: 03_hacky_hello_world/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Stopping here' ================================================ FILE: 04_safe_globals/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 04_safe_globals/Cargo.toml ================================================ [package] name = "mingo" version = "0.4.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = [] bsp_rpi4 = [] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 04_safe_globals/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 04_safe_globals/README.CN.md ================================================ # 教程 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),这是最新的。 ================================================ FILE: 04_safe_globals/README.md ================================================ # Tutorial 04 - Safe Globals ## tl;dr - A pseudo-lock is introduced. - It is a first showcase of OS synchronization primitives and enables safe access to a global data structure. ## Mutable globals in Rust When we introduced the globally usable `print!` macros in [tutorial 03], we cheated a bit. Calling `core::fmt`'s `write_fmt()` function, which takes an `&mut self`, was only working because on each call, a new instance of `QEMUOutput` was created. If we would want to preserve some state, e.g. statistics about the number of characters written, we need to make a single global instance of `QEMUOutput` (in Rust, using the `static` keyword). A `static QEMU_OUTPUT`, however, would not allow to call functions taking `&mut self`. For that, we would need a `static mut`, but calling functions that mutate state on `static mut`s is unsafe. The Rust compiler's reasoning for this is that it can then not prevent anymore that multiple cores/threads are mutating the data concurrently (it is a global, so everyone can reference it from anywhere. The borrow checker can't help here). The solution to this problem is to wrap the global into a synchronization primitive. In our case, a variant of a *MUTual EXclusion* primitive. `Mutex` is introduced as a trait in `synchronization.rs`, and implemented by the `NullLock` in the same file. In order to make the code lean for teaching purposes, it leaves out the actual architecture-specific logic for protection against concurrent access, since we don't need it as long as the kernel only executes on a single core with interrupts disabled. The `NullLock` focuses on showcasing the Rust core concept of [interior mutability]. Make sure to read up on it. I also recommend to read this article about an [accurate mental model for Rust's reference types]. If you want to compare the `NullLock` to some real-world mutex implementations, you can check out implemntations in the [spin crate] or the [parking lot crate]. [tutorial 03]: ../03_hacky_hello_world [interior mutability]: https://doc.rust-lang.org/std/cell/index.html [accurate mental model for Rust's reference types]: https://docs.rs/dtolnay/0.0.6/dtolnay/macro._02__reference_types.html [spin crate]: https://github.com/mvdnes/spin-rs [parking lot crate]: https://github.com/Amanieu/parking_lot ## Test it ```console $ make qemu [...] [0] Hello from Rust! [1] Chars written: 22 [2] Stopping here. ``` ## Diff to previous ```diff diff -uNr 03_hacky_hello_world/Cargo.toml 04_safe_globals/Cargo.toml --- 03_hacky_hello_world/Cargo.toml +++ 04_safe_globals/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.3.0" +version = "0.4.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 03_hacky_hello_world/src/bsp/raspberrypi/console.rs 04_safe_globals/src/bsp/raspberrypi/console.rs --- 03_hacky_hello_world/src/bsp/raspberrypi/console.rs +++ 04_safe_globals/src/bsp/raspberrypi/console.rs @@ -4,7 +4,7 @@ //! BSP console facilities. -use crate::console; +use crate::{console, synchronization, synchronization::NullLock}; use core::fmt; //-------------------------------------------------------------------------------------------------- @@ -12,25 +12,64 @@ //-------------------------------------------------------------------------------------------------- /// A mystical, magical device for generating QEMU output out of the void. -struct QEMUOutput; +/// +/// The mutex protected part. +struct QEMUOutputInner { + chars_written: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The main struct. +pub struct QEMUOutput { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- +impl QEMUOutputInner { + const fn new() -> QEMUOutputInner { + QEMUOutputInner { chars_written: 0 } + } + + /// Send a character. + fn write_char(&mut self, c: char) { + unsafe { + core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); + } + + self.chars_written += 1; + } +} + /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for QEMUOutput { +impl fmt::Write for QEMUOutputInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { - unsafe { - core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); + // Convert newline to carrige return + newline. + if c == '\n' { + self.write_char('\r') } + + self.write_char(c); } Ok(()) @@ -41,7 +80,39 @@ // Public Code //-------------------------------------------------------------------------------------------------- +impl QEMUOutput { + /// Create a new instance. + pub const fn new() -> QEMUOutput { + QEMUOutput { + inner: NullLock::new(QEMUOutputInner::new()), + } + } +} + /// Return a reference to the console. -pub fn console() -> impl console::interface::Write { - QEMUOutput {} +pub fn console() -> &'static dyn console::interface::All { + &QEMU_OUTPUT } + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to +/// serialize access. +impl console::interface::Write for QEMUOutput { + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } +} + +impl console::interface::Statistics for QEMUOutput { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } +} + +impl console::interface::All for QEMUOutput {} diff -uNr 03_hacky_hello_world/src/console.rs 04_safe_globals/src/console.rs --- 03_hacky_hello_world/src/console.rs +++ 04_safe_globals/src/console.rs @@ -12,12 +12,24 @@ /// Console interfaces. pub mod interface { + use core::fmt; + /// Console write functions. - /// - /// `core::fmt::Write` is exactly what we need for now. Re-export it here because - /// implementing `console::Write` gives a better hint to the reader about the - /// intention. - pub use core::fmt::Write; + pub trait Write { + /// Write a Rust format string. + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + } + + /// Console statistics. + pub trait Statistics { + /// Return the number of characters written. + fn chars_written(&self) -> usize { + 0 + } + } + + /// Trait alias for a full-fledged console. + pub trait All: Write + Statistics {} } //-------------------------------------------------------------------------------------------------- @@ -27,6 +39,6 @@ /// Return a reference to the console. /// /// This is the global console used by all printing macros. -pub fn console() -> impl interface::Write { +pub fn console() -> &'static dyn interface::All { bsp::console::console() } diff -uNr 03_hacky_hello_world/src/main.rs 04_safe_globals/src/main.rs --- 03_hacky_hello_world/src/main.rs +++ 04_safe_globals/src/main.rs @@ -109,6 +109,7 @@ #![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] +#![feature(trait_alias)] #![no_main] #![no_std] @@ -117,6 +118,7 @@ mod cpu; mod panic_wait; mod print; +mod synchronization; /// Early init code. /// @@ -124,7 +126,12 @@ /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { - println!("Hello from Rust!"); + use console::console; - panic!("Stopping here.") + println!("[0] Hello from Rust!"); + + println!("[1] Chars written: {}", console().chars_written()); + + println!("[2] Stopping here."); + cpu::wait_forever() } diff -uNr 03_hacky_hello_world/src/print.rs 04_safe_globals/src/print.rs --- 03_hacky_hello_world/src/print.rs +++ 04_safe_globals/src/print.rs @@ -13,8 +13,6 @@ #[doc(hidden)] pub fn _print(args: fmt::Arguments) { - use console::interface::Write; - console::console().write_fmt(args).unwrap(); } diff -uNr 03_hacky_hello_world/src/synchronization.rs 04_safe_globals/src/synchronization.rs --- 03_hacky_hello_world/src/synchronization.rs +++ 04_safe_globals/src/synchronization.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronization primitives. +//! +//! # Resources +//! +//! - +//! - +//! - + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Synchronization interfaces. +pub mod interface { + + /// Any object implementing this trait guarantees exclusive access to the data wrapped within + /// the Mutex for the duration of the provided closure. + pub trait Mutex { + /// The type of the data that is wrapped by this mutex. + type Data; + + /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + } +} + +/// A pseudo-lock for teaching purposes. +/// +/// In contrast to a real Mutex implementation, does not protect against concurrent access from +/// other cores to the contained data. This part is preserved for later lessons. +/// +/// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is +/// executing single-threaded, aka only running on a single core with interrupts disabled. +pub struct NullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +unsafe impl Send for NullLock where T: ?Sized + Send {} +unsafe impl Sync for NullLock where T: ?Sized + Send {} + +impl NullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl interface::Mutex for NullLock { + type Data = T; + + fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + // In a real lock, there would be code encapsulating this line that ensures that this + // mutable reference will ever only be given out once at a time. + let data = unsafe { &mut *self.data.get() }; + + f(data) + } +} ``` ================================================ FILE: 04_safe_globals/build.rs ================================================ 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())); } ================================================ FILE: 04_safe_globals/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: 04_safe_globals/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x0, MPIDR_EL1 and x0, x0, {CONST_CORE_ID_MASK} ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x0, x1 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Jump to Rust code. b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 04_safe_globals/src/_arch/aarch64/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::arch_cpu use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { loop { asm::wfe() } } ================================================ FILE: 04_safe_globals/src/bsp/raspberrypi/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP console facilities. use crate::{console, synchronization, synchronization::NullLock}; use core::fmt; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// A mystical, magical device for generating QEMU output out of the void. /// /// The mutex protected part. struct QEMUOutputInner { chars_written: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The main struct. pub struct QEMUOutput { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl QEMUOutputInner { const fn new() -> QEMUOutputInner { QEMUOutputInner { chars_written: 0 } } /// Send a character. fn write_char(&mut self, c: char) { unsafe { core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); } self.chars_written += 1; } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for QEMUOutputInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { // Convert newline to carrige return + newline. if c == '\n' { self.write_char('\r') } self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl QEMUOutput { /// Create a new instance. pub const fn new() -> QEMUOutput { QEMUOutput { inner: NullLock::new(QEMUOutputInner::new()), } } } /// Return a reference to the console. pub fn console() -> &'static dyn console::interface::All { &QEMU_OUTPUT } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. impl console::interface::Write for QEMUOutput { fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } } impl console::interface::Statistics for QEMUOutput { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } } impl console::interface::All for QEMUOutput {} ================================================ FILE: 04_safe_globals/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 04_safe_globals/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 04_safe_globals/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod console; pub mod cpu; ================================================ FILE: 04_safe_globals/src/bsp.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use raspberrypi::*; ================================================ FILE: 04_safe_globals/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. use crate::bsp; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Statistics {} } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { bsp::console::console() } ================================================ FILE: 04_safe_globals/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 04_safe_globals/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::wait_forever; ================================================ FILE: 04_safe_globals/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] #![feature(trait_alias)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod panic_wait; mod print; mod synchronization; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. unsafe fn kernel_init() -> ! { use console::console; println!("[0] Hello from Rust!"); println!("[1] Chars written: {}", console().chars_written()); println!("[2] Stopping here."); cpu::wait_forever() } ================================================ FILE: 04_safe_globals/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 04_safe_globals/src/print.rs ================================================ // 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)*)); }) } ================================================ FILE: 04_safe_globals/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 04_safe_globals/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Stopping here' ================================================ FILE: 05_drivers_gpio_uart/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 05_drivers_gpio_uart/Cargo.toml ================================================ [package] name = "mingo" version = "0.5.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 05_drivers_gpio_uart/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINITERM = ruby ../common/serial/miniterm.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DEV = --privileged -v /dev:/dev # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu miniterm clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##----------------------------------------------------------------------------- doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Connect to the target's serial ##------------------------------------------------------------------------------ miniterm: @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 05_drivers_gpio_uart/README.CN.md ================================================ # 教程 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),这是最新的。 ================================================ FILE: 05_drivers_gpio_uart/README.md ================================================ # Tutorial 05 - Drivers: GPIO and UART ## tl;dr - Drivers for the real `UART` and the `GPIO` controller are added. - **For the first time, we will be able to run the code on the real hardware** (scroll down for instructions). ## Introduction Now that we enabled safe globals in the previous tutorial, the infrastructure is laid for adding the first real device drivers. We throw out the magic QEMU console and introduce a `driver manager`, which allows the `BSP` to register device drivers with the `kernel`. ## Driver Manager The first step consists of adding a `driver subsystem` to the kernel. The corresponding code will live in `src/driver.rs`. The subsystem introduces `interface::DeviceDriver`, a common trait that every device driver will need to implement and that is known to the kernel. A global `DRIVER_MANAGER` instance (of type `DriverManager`) that is instantiated in the same file serves as the central entity that can be called to manage all things device drivers in the kernel. For example, by using the globally accessible `crate::driver::driver_manager().register_driver(...)`, any code can can register an object with static lifetime that implements the `interface::DeviceDriver` trait. During kernel init, a call to `crate::driver::driver_manager().init_drivers(...)` will let the driver manager loop over all registered drivers and kick off their initialization, and also execute an optional `post-init callback` that can be registered alongside the driver. For example, this mechanism is used to switch over to the `UART` driver as the main system console after the `UART` driver has been initialized. ## BSP Driver Implementation In `src/bsp/raspberrypi/driver.rs`, the function `init()` takes care of registering the `UART` and `GPIO` drivers. It is therefore important that during kernel init, the correct order of (i) first initializing the BSP driver subsystem, and only then (ii) calling the `driver_manager()` is followed, like the following excerpt from `main.rs` shows: ```rust unsafe fn kernel_init() -> ! { // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. ``` The drivers themselves are stored in `src/bsp/device_driver`, and can be reused between `BSP`s. The first driver added in these tutorials is the `PL011Uart` driver: It implements the `console::interface::*` traits and is from now on used as the main system console. The second driver is the `GPIO` driver, which pinmuxes (that is, routing signals from inside the `SoC` to actual HW pins) the RPi's PL011 UART accordingly. Note how the `GPIO` driver differentiates between **RPi 3** and **RPi 4**. Their HW is different, so we have to account for it in SW. The `BSP`s now also contain a memory map in `src/bsp/raspberrypi/memory.rs`. It provides the Raspberry's `MMIO` addresses which are used by the `BSP` to instantiate the respective device drivers, so that the driver code knows where to find the device's registers in memory. ## Boot it from SD card Since we have real `UART` output now, we can run the code on the real hardware. Building is differentiated between the **RPi 3** and the **RPi 4** due to before mentioned differences in the `GPIO` driver. By default, all `Makefile` targets will build for the **RPi 3**. In order to build for the the **RPi 4**, prepend `BSP=rpi4` to each target. For example: ```console $ BSP=rpi4 make $ BSP=rpi4 make doc ``` Unfortunately, QEMU does not yet support the **RPi 4**, so `BSP=rpi4 make qemu` won't work. **Some steps for preparing the SD card differ between RPi 3 and RPi 4, so be careful in the following.** ### Common for both 1. Make a single `FAT32` partition named `boot`. 2. On the card, generate a file named `config.txt` with the following contents: ```txt arm_64bit=1 init_uart_clock=48000000 ``` ### RPi 3 3. Copy the following files from the [Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot) onto the SD card: - [bootcode.bin](https://github.com/raspberrypi/firmware/raw/master/boot/bootcode.bin) - [fixup.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup.dat) - [start.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start.elf) 4. Run `make`. ### RPi 4 3. Copy the following files from the [Raspberry Pi firmware repo](https://github.com/raspberrypi/firmware/tree/master/boot) onto the SD card: - [fixup4.dat](https://github.com/raspberrypi/firmware/raw/master/boot/fixup4.dat) - [start4.elf](https://github.com/raspberrypi/firmware/raw/master/boot/start4.elf) - [bcm2711-rpi-4-b.dtb](https://github.com/raspberrypi/firmware/raw/master/boot/bcm2711-rpi-4-b.dtb) 4. Run `BSP=rpi4 make`. _**Note**: Should it not work on your RPi 4, try renaming `start4.elf` to `start.elf` (without the 4) on the SD card._ ### Common again 5. Copy the `kernel8.img` onto the SD card and insert it back into the RPi. 6. Run the `miniterm` target, which opens the UART device on the host: ```console $ make miniterm ``` > ❗ **NOTE**: `Miniterm` assumes a default serial device name of `/dev/ttyUSB0`. Depending on your > host operating system, the device name might differ. For example, on `macOS`, it might be > something like `/dev/tty.usbserial-0001`. In this case, please give the name explicitly: ```console $ DEV_SERIAL=/dev/tty.usbserial-0001 make miniterm ``` 7. Connect the USB serial to your host PC. - Wiring diagram at [top-level README](../README.md#-usb-serial-output). - **NOTE**: TX (transmit) wire connects to the RX (receive) pin. - Make sure that you **DID NOT** connect the power pin of the USB serial. Only RX/TX and GND. 8. Connect the RPi to the (USB) power cable and observe the output: ```console Miniterm 1.0 [MT] ⏳ Waiting for /dev/ttyUSB0 [MT] ✅ Serial connected [0] mingo version 0.5.0 [1] Booting on: Raspberry Pi 3 [2] Drivers loaded: 1. BCM PL011 UART 2. BCM GPIO [3] Chars written: 117 [4] Echoing input now ``` 8. Exit by pressing ctrl-c. ## Diff to previous ```diff diff -uNr 04_safe_globals/Cargo.toml 05_drivers_gpio_uart/Cargo.toml --- 04_safe_globals/Cargo.toml +++ 05_drivers_gpio_uart/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.4.0" +version = "0.5.0" authors = ["Andre Richter "] edition = "2021" @@ -9,8 +9,8 @@ [features] default = [] -bsp_rpi3 = [] -bsp_rpi4 = [] +bsp_rpi3 = ["tock-registers"] +bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" @@ -22,6 +22,9 @@ [dependencies] +# Optional dependencies +tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } + # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } diff -uNr 04_safe_globals/Makefile 05_drivers_gpio_uart/Makefile --- 04_safe_globals/Makefile +++ 05_drivers_gpio_uart/Makefile @@ -13,6 +13,9 @@ # Default to the RPi3. BSP ?= rpi3 +# Default to a serial device name that is common in Linux. +DEV_SERIAL ?= /dev/ttyUSB0 + ##-------------------------------------------------------------------------------------------------- @@ -88,6 +91,7 @@ EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb +EXEC_MINITERM = ruby ../common/serial/miniterm.rb ##------------------------------------------------------------------------------ ## Dockerization @@ -95,18 +99,26 @@ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DEV = --privileged -v /dev:/dev # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +# Dockerize commands, which require USB device passthrough, only on Linux. +ifeq ($(shell uname -s),Linux) + DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) + + DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +endif + ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- -.PHONY: all doc qemu clippy clean readelf objdump nm check +.PHONY: all doc qemu miniterm clippy clean readelf objdump nm check all: $(KERNEL_BIN) @@ -156,9 +168,16 @@ qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + endif ##------------------------------------------------------------------------------ +## Connect to the target's serial +##------------------------------------------------------------------------------ +miniterm: + @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) + +##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: diff -uNr 04_safe_globals/src/_arch/aarch64/cpu.rs 05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs --- 04_safe_globals/src/_arch/aarch64/cpu.rs +++ 05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs @@ -17,6 +17,17 @@ // Public Code //-------------------------------------------------------------------------------------------------- +pub use asm::nop; + +/// Spin for `n` cycles. +#[cfg(feature = "bsp_rpi3")] +#[inline(always)] +pub fn spin_for_cycles(n: usize) { + for _ in 0..n { + asm::nop(); + } +} + /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs --- 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! GPIO Driver. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, + synchronization::NullLock, +}; +use tock_registers::{ + interfaces::{ReadWriteable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// GPIO registers. +// +// Descriptions taken from +// - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf +// - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf +register_bitfields! { + u32, + + /// GPIO Function Select 1 + GPFSEL1 [ + /// Pin 15 + FSEL15 OFFSET(15) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART RX + + ], + + /// Pin 14 + FSEL14 OFFSET(12) NUMBITS(3) [ + Input = 0b000, + Output = 0b001, + AltFunc0 = 0b100 // PL011 UART TX + ] + ], + + /// GPIO Pull-up/down Register + /// + /// BCM2837 only. + GPPUD [ + /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. + PUD OFFSET(0) NUMBITS(2) [ + Off = 0b00, + PullDown = 0b01, + PullUp = 0b10 + ] + ], + + /// GPIO Pull-up/down Clock Register 0 + /// + /// BCM2837 only. + GPPUDCLK0 [ + /// Pin 15 + PUDCLK15 OFFSET(15) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ], + + /// Pin 14 + PUDCLK14 OFFSET(14) NUMBITS(1) [ + NoEffect = 0, + AssertClock = 1 + ] + ], + + /// GPIO Pull-up / Pull-down Register 0 + /// + /// BCM2711 only. + GPIO_PUP_PDN_CNTRL_REG0 [ + /// Pin 15 + GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ], + + /// Pin 14 + GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ + NoResistor = 0b00, + PullUp = 0b01 + ] + ] +} + +register_structs! { + #[allow(non_snake_case)] + RegisterBlock { + (0x00 => _reserved1), + (0x04 => GPFSEL1: ReadWrite), + (0x08 => _reserved2), + (0x94 => GPPUD: ReadWrite), + (0x98 => GPPUDCLK0: ReadWrite), + (0x9C => _reserved3), + (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), + (0xE8 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +struct GPIOInner { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GPIO HW. +pub struct GPIO { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl GPIOInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + fn disable_pud_14_15_bcm2837(&mut self) { + use crate::cpu; + + // Make an educated guess for a good delay value (Sequence described in the BCM2837 + // peripherals PDF). + // + // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. + // - The Linux 2837 GPIO driver waits 1 µs between the steps. + // + // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs + // would the CPU be clocked at 2 GHz. + const DELAY: usize = 2000; + + self.registers.GPPUD.write(GPPUD::PUD::Off); + cpu::spin_for_cycles(DELAY); + + self.registers + .GPPUDCLK0 + .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); + cpu::spin_for_cycles(DELAY); + + self.registers.GPPUD.write(GPPUD::PUD::Off); + self.registers.GPPUDCLK0.set(0); + } + + /// Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi4")] + fn disable_pud_14_15_bcm2711(&mut self) { + self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, + ); + } + + /// Map PL011 UART as standard output. + /// + /// TX to pin 14 + /// RX to pin 15 + pub fn map_pl011_uart(&mut self) { + // Select the UART on pins 14 and 15. + self.registers + .GPFSEL1 + .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); + + // Disable pull-up/down on pins 14 and 15. + #[cfg(feature = "bsp_rpi3")] + self.disable_pud_14_15_bcm2837(); + + #[cfg(feature = "bsp_rpi4")] + self.disable_pud_14_15_bcm2711(); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GPIO { + pub const COMPATIBLE: &'static str = "BCM GPIO"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + } + } + + /// Concurrency safe version of `GPIOInner.map_pl011_uart()` + pub fn map_pl011_uart(&self) { + self.inner.lock(|inner| inner.map_pl011_uart()) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for GPIO { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} diff -uNr 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs --- 04_safe_globals/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! PL011 UART driver. +//! +//! # Resources +//! +//! - +//! - + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, + synchronization::NullLock, +}; +use core::fmt; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// PL011 UART registers. +// +// Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. +register_bitfields! { + u32, + + /// Flag Register. + FR [ + /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// Line Control Register, LCR_H. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. + /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. + /// - This bit does not indicate if there is data in the transmit shift register. + TXFE OFFSET(7) NUMBITS(1) [], + + /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. + /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. + TXFF OFFSET(5) NUMBITS(1) [], + + /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the + /// LCR_H Register. + /// + /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. + /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. + RXFE OFFSET(4) NUMBITS(1) [], + + /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains + /// set until the complete byte, including all the stop bits, has been sent from the shift + /// register. + /// + /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether + /// the UART is enabled or not. + BUSY OFFSET(3) NUMBITS(1) [] + ], + + /// Integer Baud Rate Divisor. + IBRD [ + /// The integer baud rate divisor. + BAUD_DIVINT OFFSET(0) NUMBITS(16) [] + ], + + /// Fractional Baud Rate Divisor. + FBRD [ + /// The fractional baud rate divisor. + BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] + ], + + /// Line Control Register. + LCR_H [ + /// Word length. These bits indicate the number of data bits transmitted or received in a + /// frame. + #[allow(clippy::enum_variant_names)] + WLEN OFFSET(5) NUMBITS(2) [ + FiveBit = 0b00, + SixBit = 0b01, + SevenBit = 0b10, + EightBit = 0b11 + ], + + /// Enable FIFOs: + /// + /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding + /// registers. + /// + /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). + FEN OFFSET(4) NUMBITS(1) [ + FifosDisabled = 0, + FifosEnabled = 1 + ] + ], + + /// Control Register. + CR [ + /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. + /// Data reception occurs for either UART signals or SIR signals depending on the setting of + /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the + /// current character before stopping. + RXE OFFSET(9) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. + /// Data transmission occurs for either UART signals, or SIR signals depending on the + /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it + /// completes the current character before stopping. + TXE OFFSET(8) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// UART enable: + /// + /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or + /// reception, it completes the current character before stopping. + /// + /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals + /// or SIR signals depending on the setting of the SIREN bit + UARTEN OFFSET(0) NUMBITS(1) [ + /// If the UART is disabled in the middle of transmission or reception, it completes the + /// current character before stopping. + Disabled = 0, + Enabled = 1 + ] + ], + + /// Interrupt Clear Register. + ICR [ + /// Meta field for all pending interrupts. + ALL OFFSET(0) NUMBITS(11) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x00 => DR: ReadWrite), + (0x04 => _reserved1), + (0x18 => FR: ReadOnly), + (0x1c => _reserved2), + (0x24 => IBRD: WriteOnly), + (0x28 => FBRD: WriteOnly), + (0x2c => LCR_H: WriteOnly), + (0x30 => CR: WriteOnly), + (0x34 => _reserved3), + (0x44 => ICR: WriteOnly), + (0x48 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +#[derive(PartialEq)] +enum BlockingMode { + Blocking, + NonBlocking, +} + +struct PL011UartInner { + registers: Registers, + chars_written: usize, + chars_read: usize, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the UART. +pub struct PL011Uart { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PL011UartInner { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + chars_written: 0, + chars_read: 0, + } + } + + /// Set up baud rate and characteristics. + /// + /// This results in 8N1 and 921_600 baud. + /// + /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): + /// `(48_000_000 / 16) / 921_600 = 3.2552083`. + /// + /// This means the integer part is `3` and goes into the `IBRD`. + /// The fractional part is `0.2552083`. + /// + /// `FBRD` calculation according to the PL011 Technical Reference Manual: + /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. + /// + /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a + /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. + /// + /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16modulo`. + pub fn init(&mut self) { + // Execution can arrive here while there are still characters queued in the TX FIFO and + // actively being sent out by the UART hardware. If the UART is turned off in this case, + // those queued characters would be lost. + // + // For example, this can happen during runtime on a call to panic!(), because panic!() + // initializes its own UART instance and calls init(). + // + // Hence, flush first to ensure all pending characters are transmitted. + self.flush(); + + // Turn the UART off temporarily. + self.registers.CR.set(0); + + // Clear all pending interrupts. + self.registers.ICR.write(ICR::ALL::CLEAR); + + // From the PL011 Technical Reference Manual: + // + // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is + // updated on a single write strobe generated by a LCR_H write. So, to internally update the + // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. + // + // Set the baud rate, 8N1 and FIFO enabled. + self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); + self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); + self.registers + .LCR_H + .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + + // Turn the UART on. + self.registers + .CR + .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); + } + + /// Send a character. + fn write_char(&mut self, c: char) { + // Spin while TX FIFO full is set, waiting for an empty slot. + while self.registers.FR.matches_all(FR::TXFF::SET) { + cpu::nop(); + } + + // Write the character to the buffer. + self.registers.DR.set(c as u32); + + self.chars_written += 1; + } + + /// Block execution until the last buffered character has been physically put on the TX wire. + fn flush(&self) { + // Spin until the busy bit is cleared. + while self.registers.FR.matches_all(FR::BUSY::SET) { + cpu::nop(); + } + } + + /// Retrieve a character. + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + // If RX FIFO is empty, + if self.registers.FR.matches_all(FR::RXFE::SET) { + // immediately return in non-blocking mode. + if blocking_mode == BlockingMode::NonBlocking { + return None; + } + + // Otherwise, wait until a char was received. + while self.registers.FR.matches_all(FR::RXFE::SET) { + cpu::nop(); + } + } + + // Read one character. + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } + + // Update statistics. + self.chars_read += 1; + + Some(ret) + } +} + +/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are +/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, +/// we get `write_fmt()` automatically. +/// +/// The function takes an `&mut self`, so it must be implemented for the inner struct. +/// +/// See [`src/print.rs`]. +/// +/// [`src/print.rs`]: ../../print/index.html +impl fmt::Write for PL011UartInner { + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + + Ok(()) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PL011Uart { + pub const COMPATIBLE: &'static str = "BCM PL011 UART"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::Mutex; + +impl driver::interface::DeviceDriver for PL011Uart { + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + + Ok(()) + } +} + +impl console::interface::Write for PL011Uart { + /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to + /// serialize access. + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase + // readability. + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + fn flush(&self) { + // Spin until TX FIFO empty is set. + self.inner.lock(|inner| inner.flush()); + } +} + +impl console::interface::Read for PL011Uart { + fn read_char(&self) -> char { + self.inner + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + } + + fn clear_rx(&self) { + // Read from the RX FIFO until it is indicating empty. + while self + .inner + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .is_some() + {} + } +} + +impl console::interface::Statistics for PL011Uart { + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } + + fn chars_read(&self) -> usize { + self.inner.lock(|inner| inner.chars_read) + } +} + +impl console::interface::All for PL011Uart {} diff -uNr 04_safe_globals/src/bsp/device_driver/bcm.rs 05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs --- 04_safe_globals/src/bsp/device_driver/bcm.rs +++ 05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BCM driver top level. + +mod bcm2xxx_gpio; +mod bcm2xxx_pl011_uart; + +pub use bcm2xxx_gpio::*; +pub use bcm2xxx_pl011_uart::*; diff -uNr 04_safe_globals/src/bsp/device_driver/common.rs 05_drivers_gpio_uart/src/bsp/device_driver/common.rs --- 04_safe_globals/src/bsp/device_driver/common.rs +++ 05_drivers_gpio_uart/src/bsp/device_driver/common.rs @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Common device driver code. + +use core::{marker::PhantomData, ops}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct MMIODerefWrapper { + start_addr: usize, + phantom: PhantomData T>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl MMIODerefWrapper { + /// Create an instance. + pub const unsafe fn new(start_addr: usize) -> Self { + Self { + start_addr, + phantom: PhantomData, + } + } +} + +impl ops::Deref for MMIODerefWrapper { + type Target = T; + + fn deref(&self) -> &Self::Target { + unsafe { &*(self.start_addr as *const _) } + } +} diff -uNr 04_safe_globals/src/bsp/device_driver.rs 05_drivers_gpio_uart/src/bsp/device_driver.rs --- 04_safe_globals/src/bsp/device_driver.rs +++ 05_drivers_gpio_uart/src/bsp/device_driver.rs @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Device driver. + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +mod bcm; +mod common; + +#[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] +pub use bcm::*; diff -uNr 04_safe_globals/src/bsp/raspberrypi/console.rs 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs --- 04_safe_globals/src/bsp/raspberrypi/console.rs +++ 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs @@ -4,115 +4,13 @@ //! BSP console facilities. -use crate::{console, synchronization, synchronization::NullLock}; -use core::fmt; - -//-------------------------------------------------------------------------------------------------- -// Private Definitions -//-------------------------------------------------------------------------------------------------- - -/// A mystical, magical device for generating QEMU output out of the void. -/// -/// The mutex protected part. -struct QEMUOutputInner { - chars_written: usize, -} - -//-------------------------------------------------------------------------------------------------- -// Public Definitions -//-------------------------------------------------------------------------------------------------- - -/// The main struct. -pub struct QEMUOutput { - inner: NullLock, -} - -//-------------------------------------------------------------------------------------------------- -// Global instances -//-------------------------------------------------------------------------------------------------- - -static QEMU_OUTPUT: QEMUOutput = QEMUOutput::new(); - -//-------------------------------------------------------------------------------------------------- -// Private Code -//-------------------------------------------------------------------------------------------------- - -impl QEMUOutputInner { - const fn new() -> QEMUOutputInner { - QEMUOutputInner { chars_written: 0 } - } - - /// Send a character. - fn write_char(&mut self, c: char) { - unsafe { - core::ptr::write_volatile(0x3F20_1000 as *mut u8, c as u8); - } - - self.chars_written += 1; - } -} - -/// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are -/// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, -/// we get `write_fmt()` automatically. -/// -/// The function takes an `&mut self`, so it must be implemented for the inner struct. -/// -/// See [`src/print.rs`]. -/// -/// [`src/print.rs`]: ../../print/index.html -impl fmt::Write for QEMUOutputInner { - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - // Convert newline to carrige return + newline. - if c == '\n' { - self.write_char('\r') - } - - self.write_char(c); - } - - Ok(()) - } -} +use crate::console; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -impl QEMUOutput { - /// Create a new instance. - pub const fn new() -> QEMUOutput { - QEMUOutput { - inner: NullLock::new(QEMUOutputInner::new()), - } - } -} - /// Return a reference to the console. pub fn console() -> &'static dyn console::interface::All { - &QEMU_OUTPUT -} - -//------------------------------------------------------------------------------ -// OS Interface Code -//------------------------------------------------------------------------------ -use synchronization::interface::Mutex; - -/// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to -/// serialize access. -impl console::interface::Write for QEMUOutput { - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase - // readability. - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } -} - -impl console::interface::Statistics for QEMUOutput { - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } + &super::driver::PL011_UART } - -impl console::interface::All for QEMUOutput {} diff -uNr 04_safe_globals/src/bsp/raspberrypi/driver.rs 05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs --- 04_safe_globals/src/bsp/raspberrypi/driver.rs +++ 05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP driver support. + +use super::memory::map::mmio; +use crate::{bsp::device_driver, console, driver as generic_driver}; +use core::sync::atomic::{AtomicBool, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static PL011_UART: device_driver::PL011Uart = + unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; +static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// This must be called only after successful init of the UART driver. +fn post_init_uart() -> Result<(), &'static str> { + console::register_console(&PL011_UART); + + Ok(()) +} + +/// This must be called only after successful init of the GPIO driver. +fn post_init_gpio() -> Result<(), &'static str> { + GPIO.map_pl011_uart(); + Ok(()) +} + +fn driver_uart() -> Result<(), &'static str> { + let uart_descriptor = + generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + generic_driver::driver_manager().register_driver(uart_descriptor); + + Ok(()) +} + +fn driver_gpio() -> Result<(), &'static str> { + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + generic_driver::driver_manager().register_driver(gpio_descriptor); + + Ok(()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Initialize the driver subsystem. +/// +/// # Safety +/// +/// See child function calls. +pub unsafe fn init() -> Result<(), &'static str> { + static INIT_DONE: AtomicBool = AtomicBool::new(false); + if INIT_DONE.load(Ordering::Relaxed) { + return Err("Init already done"); + } + + driver_uart()?; + driver_gpio()?; + + INIT_DONE.store(true, Ordering::Relaxed); + Ok(()) +} diff -uNr 04_safe_globals/src/bsp/raspberrypi/memory.rs 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs --- 04_safe_globals/src/bsp/raspberrypi/memory.rs +++ 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management. + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The board's physical memory map. +#[rustfmt::skip] +pub(super) mod map { + + pub const GPIO_OFFSET: usize = 0x0020_0000; + pub const UART_OFFSET: usize = 0x0020_1000; + + /// Physical devices. + #[cfg(feature = "bsp_rpi3")] + pub mod mmio { + use super::*; + + pub const START: usize = 0x3F00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } + + /// Physical devices. + #[cfg(feature = "bsp_rpi4")] + pub mod mmio { + use super::*; + + pub const START: usize = 0xFE00_0000; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + } +} diff -uNr 04_safe_globals/src/bsp/raspberrypi.rs 05_drivers_gpio_uart/src/bsp/raspberrypi.rs --- 04_safe_globals/src/bsp/raspberrypi.rs +++ 05_drivers_gpio_uart/src/bsp/raspberrypi.rs @@ -4,5 +4,23 @@ //! Top-level BSP file for the Raspberry Pi 3 and 4. -pub mod console; pub mod cpu; +pub mod driver; +pub mod memory; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Board identification. +pub fn board_name() -> &'static str { + #[cfg(feature = "bsp_rpi3")] + { + "Raspberry Pi 3" + } + + #[cfg(feature = "bsp_rpi4")] + { + "Raspberry Pi 4" + } +} diff -uNr 04_safe_globals/src/bsp.rs 05_drivers_gpio_uart/src/bsp.rs --- 04_safe_globals/src/bsp.rs +++ 05_drivers_gpio_uart/src/bsp.rs @@ -4,6 +4,8 @@ //! Conditional reexporting of Board Support Packages. +mod device_driver; + #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; diff -uNr 04_safe_globals/src/console/null_console.rs 05_drivers_gpio_uart/src/console/null_console.rs --- 04_safe_globals/src/console/null_console.rs +++ 05_drivers_gpio_uart/src/console/null_console.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null console. + +use super::interface; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullConsole; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_CONSOLE: NullConsole = NullConsole {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::Write for NullConsole { + fn write_char(&self, _c: char) {} + + fn write_fmt(&self, _args: fmt::Arguments) -> fmt::Result { + fmt::Result::Ok(()) + } + + fn flush(&self) {} +} + +impl interface::Read for NullConsole { + fn clear_rx(&self) {} +} + +impl interface::Statistics for NullConsole {} +impl interface::All for NullConsole {} diff -uNr 04_safe_globals/src/console.rs 05_drivers_gpio_uart/src/console.rs --- 04_safe_globals/src/console.rs +++ 05_drivers_gpio_uart/src/console.rs @@ -4,7 +4,9 @@ //! System console. -use crate::bsp; +mod null_console; + +use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -16,8 +18,25 @@ /// Console write functions. pub trait Write { + /// Write a single character. + fn write_char(&self, c: char); + /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + + /// Block until the last buffered character has been physically put on the TX wire. + fn flush(&self); + } + + /// Console read functions. + pub trait Read { + /// Read a single character. + fn read_char(&self) -> char { + ' ' + } + + /// Clear RX buffers, if any. + fn clear_rx(&self); } /// Console statistics. @@ -26,19 +45,37 @@ fn chars_written(&self) -> usize { 0 } + + /// Return the number of characters read. + fn chars_read(&self) -> usize { + 0 + } } /// Trait alias for a full-fledged console. - pub trait All: Write + Statistics {} + pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = + NullLock::new(&null_console::NULL_CONSOLE); + +//-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +/// Register a new console. +pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { + CUR_CONSOLE.lock(|con| *con = new_console); +} -/// Return a reference to the console. +/// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { - bsp::console::console() + CUR_CONSOLE.lock(|con| *con) } diff -uNr 04_safe_globals/src/cpu.rs 05_drivers_gpio_uart/src/cpu.rs --- 04_safe_globals/src/cpu.rs +++ 05_drivers_gpio_uart/src/cpu.rs @@ -13,4 +13,7 @@ //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- -pub use arch_cpu::wait_forever; +pub use arch_cpu::{nop, wait_forever}; + +#[cfg(feature = "bsp_rpi3")] +pub use arch_cpu::spin_for_cycles; diff -uNr 04_safe_globals/src/driver.rs 05_drivers_gpio_uart/src/driver.rs --- 04_safe_globals/src/driver.rs +++ 05_drivers_gpio_uart/src/driver.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Driver support. + +use crate::{ + println, + synchronization::{interface::Mutex, NullLock}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NUM_DRIVERS: usize = 5; + +struct DriverManagerInner { + next_index: usize, + descriptors: [Option; NUM_DRIVERS], +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Driver interfaces. +pub mod interface { + /// Device Driver functions. + pub trait DeviceDriver { + /// Return a compatibility string for identifying the driver. + fn compatible(&self) -> &'static str; + + /// Called by the kernel to bring up the device. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + unsafe fn init(&self) -> Result<(), &'static str> { + Ok(()) + } + } +} + +/// Tpye to be used as an optional callback after a driver's init() has run. +pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; + +/// A descriptor for device drivers. +#[derive(Copy, Clone)] +pub struct DeviceDriverDescriptor { + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, +} + +/// Provides device driver management functions. +pub struct DriverManager { + inner: NullLock, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static DRIVER_MANAGER: DriverManager = DriverManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DriverManagerInner { + /// Create an instance. + pub const fn new() -> Self { + Self { + next_index: 0, + descriptors: [None; NUM_DRIVERS], + } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl DeviceDriverDescriptor { + /// Create an instance. + pub fn new( + device_driver: &'static (dyn interface::DeviceDriver + Sync), + post_init_callback: Option, + ) -> Self { + Self { + device_driver, + post_init_callback, + } + } +} + +/// Return a reference to the global DriverManager. +pub fn driver_manager() -> &'static DriverManager { + &DRIVER_MANAGER +} + +impl DriverManager { + /// Create an instance. + pub const fn new() -> Self { + Self { + inner: NullLock::new(DriverManagerInner::new()), + } + } + + /// Register a device driver with the kernel. + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.lock(|inner| { + inner.descriptors[inner.next_index] = Some(descriptor); + inner.next_index += 1; + }) + } + + /// Helper for iterating over registered drivers. + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.lock(|inner| { + inner + .descriptors + .iter() + .filter_map(|x| x.as_ref()) + .for_each(f) + }) + } + + /// Fully initialize all drivers. + /// + /// # Safety + /// + /// - During init, drivers might do stuff with system-wide impact. + pub unsafe fn init_drivers(&self) { + self.for_each_descriptor(|descriptor| { + // 1. Initialize driver. + if let Err(x) = descriptor.device_driver.init() { + panic!( + "Error initializing driver: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + + // 2. Call corresponding post init callback. + if let Some(callback) = &descriptor.post_init_callback { + if let Err(x) = callback() { + panic!( + "Error during driver post-init callback: {}: {}", + descriptor.device_driver.compatible(), + x + ); + } + } + }); + } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + println!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } +} diff -uNr 04_safe_globals/src/main.rs 05_drivers_gpio_uart/src/main.rs --- 04_safe_globals/src/main.rs +++ 05_drivers_gpio_uart/src/main.rs @@ -106,6 +106,7 @@ //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. +#![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] @@ -116,6 +117,7 @@ mod bsp; mod console; mod cpu; +mod driver; mod panic_wait; mod print; mod synchronization; @@ -125,13 +127,42 @@ /// # Safety /// /// - Only a single core must be active and running this function. +/// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { - use console::console; + // Initialize the BSP driver subsystem. + if let Err(x) = bsp::driver::init() { + panic!("Error initializing BSP driver subsystem: {}", x); + } + + // Initialize all device drivers. + driver::driver_manager().init_drivers(); + // println! is usable from here on. - println!("[0] Hello from Rust!"); + // Transition from unsafe to safe. + kernel_main() +} - println!("[1] Chars written: {}", console().chars_written()); +/// The main function running after the early init. +fn kernel_main() -> ! { + use console::console; - println!("[2] Stopping here."); - cpu::wait_forever() + println!( + "[0] {} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + println!("[1] Booting on: {}", bsp::board_name()); + + println!("[2] Drivers loaded:"); + driver::driver_manager().enumerate(); + + println!("[3] Chars written: {}", console().chars_written()); + println!("[4] Echoing input now"); + + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); + loop { + let c = console().read_char(); + console().write_char(c); + } } diff -uNr 04_safe_globals/tests/boot_test_string.rb 05_drivers_gpio_uart/tests/boot_test_string.rb --- 04_safe_globals/tests/boot_test_string.rb +++ 05_drivers_gpio_uart/tests/boot_test_string.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -EXPECTED_PRINT = 'Stopping here' +EXPECTED_PRINT = 'Echoing input now' ``` ================================================ FILE: 05_drivers_gpio_uart/build.rs ================================================ 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())); } ================================================ FILE: 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x0, MPIDR_EL1 and x0, x0, {CONST_CORE_ID_MASK} ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x0, x1 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Jump to Rust code. b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 05_drivers_gpio_uart/src/_arch/aarch64/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::arch_cpu use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- pub use asm::nop; /// Spin for `n` cycles. #[cfg(feature = "bsp_rpi3")] #[inline(always)] pub fn spin_for_cycles(n: usize) { for _ in 0..n { asm::nop(); } } /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { loop { asm::wfe() } } ================================================ FILE: 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::cpu; // Make an educated guess for a good delay value (Sequence described in the BCM2837 // peripherals PDF). // // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. // - The Linux 2837 GPIO driver waits 1 µs between the steps. // // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs // would the CPU be clocked at 2 GHz. const DELAY: usize = 2000; self.registers.GPPUD.write(GPPUD::PUD::Off); cpu::spin_for_cycles(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); cpu::spin_for_cycles(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 05_drivers_gpio_uart/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 05_drivers_gpio_uart/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 05_drivers_gpio_uart/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs ================================================ // 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 } ================================================ FILE: 05_drivers_gpio_uart/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 05_drivers_gpio_uart/src/bsp/raspberrypi/driver.rs ================================================ // 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(()) } ================================================ FILE: 05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } } ================================================ FILE: 05_drivers_gpio_uart/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 05_drivers_gpio_uart/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 05_drivers_gpio_uart/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 05_drivers_gpio_uart/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 05_drivers_gpio_uart/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 05_drivers_gpio_uart/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; #[cfg(feature = "bsp_rpi3")] pub use arch_cpu::spin_for_cycles; ================================================ FILE: 05_drivers_gpio_uart/src/driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Driver support. use crate::{ println, synchronization::{interface::Mutex, NullLock}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- const NUM_DRIVERS: usize = 5; struct DriverManagerInner { next_index: usize, descriptors: [Option; NUM_DRIVERS], } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Driver interfaces. pub mod interface { /// Device Driver functions. pub trait DeviceDriver { /// Return a compatibility string for identifying the driver. fn compatible(&self) -> &'static str; /// Called by the kernel to bring up the device. /// /// # Safety /// /// - During init, drivers might do stuff with system-wide impact. unsafe fn init(&self) -> Result<(), &'static str> { Ok(()) } } } /// Tpye to be used as an optional callback after a driver's init() has run. pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; /// A descriptor for device drivers. #[derive(Copy, Clone)] pub struct DeviceDriverDescriptor { device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, } /// Provides device driver management functions. pub struct DriverManager { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static DRIVER_MANAGER: DriverManager = DriverManager::new(); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl DriverManagerInner { /// Create an instance. pub const fn new() -> Self { Self { next_index: 0, descriptors: [None; NUM_DRIVERS], } } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl DeviceDriverDescriptor { /// Create an instance. pub fn new( device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, ) -> Self { Self { device_driver, post_init_callback, } } } /// Return a reference to the global DriverManager. pub fn driver_manager() -> &'static DriverManager { &DRIVER_MANAGER } impl DriverManager { /// Create an instance. pub const fn new() -> Self { Self { inner: NullLock::new(DriverManagerInner::new()), } } /// Register a device driver with the kernel. pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { self.inner.lock(|inner| { inner.descriptors[inner.next_index] = Some(descriptor); inner.next_index += 1; }) } /// Helper for iterating over registered drivers. fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { self.inner.lock(|inner| { inner .descriptors .iter() .filter_map(|x| x.as_ref()) .for_each(f) }) } /// Fully initialize all drivers. /// /// # Safety /// /// - During init, drivers might do stuff with system-wide impact. pub unsafe fn init_drivers(&self) { self.for_each_descriptor(|descriptor| { // 1. Initialize driver. if let Err(x) = descriptor.device_driver.init() { panic!( "Error initializing driver: {}: {}", descriptor.device_driver.compatible(), x ); } // 2. Call corresponding post init callback. if let Some(callback) = &descriptor.post_init_callback { if let Err(x) = callback() { panic!( "Error during driver post-init callback: {}: {}", descriptor.device_driver.compatible(), x ); } } }); } /// Enumerate all registered device drivers. pub fn enumerate(&self) { let mut i: usize = 1; self.for_each_descriptor(|descriptor| { println!(" {}. {}", i, descriptor.device_driver.compatible()); i += 1; }); } } ================================================ FILE: 05_drivers_gpio_uart/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] #![feature(trait_alias)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod driver; mod panic_wait; mod print; mod synchronization; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { use console::console; println!( "[0] {} version {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION") ); println!("[1] Booting on: {}", bsp::board_name()); println!("[2] Drivers loaded:"); driver::driver_manager().enumerate(); println!("[3] Chars written: {}", console().chars_written()); println!("[4] Echoing input now"); // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { let c = console().read_char(); console().write_char(c); } } ================================================ FILE: 05_drivers_gpio_uart/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 05_drivers_gpio_uart/src/print.rs ================================================ // 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)*)); }) } ================================================ FILE: 05_drivers_gpio_uart/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 05_drivers_gpio_uart/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 06_uart_chainloader/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 06_uart_chainloader/Cargo.toml ================================================ [package] name = "mingo" version = "0.6.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 06_uart_chainloader/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_MINIPUSH = ruby tests/chainboot_test.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DEV = --privileged -v /dev:/dev # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu qemuasm: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) qemuasm: $(KERNEL_BIN) $(call color_header, "Launching QEMU with ASM output") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_MINIPUSH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) \ -kernel $(KERNEL_BIN) $(CHAINBOOT_DEMO_PAYLOAD) test: test_boot endif ================================================ FILE: 06_uart_chainloader/README.CN.md ================================================ # 教程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),这是最新的。 ================================================ FILE: 06_uart_chainloader/README.md ================================================ # Tutorial 06 - UART Chainloader ## tl;dr - Running from an SD card was a nice experience, but it would be extremely tedious to do it for every new binary. So let's write a [chainloader]. - This will be the last binary you need to put on the SD card. Each following tutorial will provide a `chainboot` target in the `Makefile` that lets you conveniently load the kernel over `UART`. [chainloader]: https://en.wikipedia.org/wiki/Chain_loading ## Note Please note that there is stuff going on in this tutorial that is very hard to grasp by only looking at the source code changes. The gist of it is that in `boot.s`, we are writing a piece of [position independent code] which automatically determines where the firmware has loaded the binary (`0x8_0000`), and where it was linked to (`0x200_0000`, see `kernel.ld`). The binary then copies itself from loaded to linked address (aka "relocating" itself), and then jumps to the relocated version of `_start_rust()`. Since the chainloader has put itself "out of the way" now, it can now receive another kernel binary from the `UART` and copy it to the standard load address of the RPi firmware at `0x8_0000`. Finally, it jumps to `0x8_0000` and the newly loaded binary transparently executes as if it had been loaded from SD card all along. Please bear with me until I find the time to write it all down here elaborately. For the time being, please see this tutorial as an enabler for a convenience feature that allows booting the following tutorials in a quick manner. _For those keen to get a deeper understanding, it could make sense to skip forward to [Chapter 15](../15_virtual_mem_part3_precomputed_tables) and read the first half of the README, where `Load Address != Link Address` is discussed_. [position independent code]: https://en.wikipedia.org/wiki/Position-independent_code ## Install and test it Our chainloader is called `MiniLoad` and is inspired by [raspbootin]. You can try it with this tutorial already: 1. Depending on your target hardware, run:`make` or `BSP=rpi4 make`. 1. Copy `kernel8.img` to the SD card and put the SD card back into your RPi. 1. Run `make chainboot` or `BSP=rpi4 make chainboot`. 1. Connect the USB serial to your host PC. - Wiring diagram at [top-level README](../README.md#-usb-serial-output). - Make sure that you **DID NOT** connect the power pin of the USB serial. Only RX/TX and GND. 1. Connect the RPi to the (USB) power cable. 1. Observe the loader fetching a kernel over `UART`: > ❗ **NOTE**: `make chainboot` assumes a default serial device name of `/dev/ttyUSB0`. Depending on > your host operating system, the device name might differ. For example, on `macOS`, it might be > something like `/dev/tty.usbserial-0001`. In this case, please give the name explicitly: ```console $ DEV_SERIAL=/dev/tty.usbserial-0001 make chainboot ``` [raspbootin]: https://github.com/mrvn/raspbootin ```console $ make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 7 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [0] mingo version 0.5.0 [1] Booting on: Raspberry Pi 3 [2] Drivers loaded: 1. BCM PL011 UART 2. BCM GPIO [3] Chars written: 117 [4] Echoing input now ``` In this tutorial, a version of the kernel from the previous tutorial is loaded for demo purposes. In subsequent tutorials, it will be the working directory's kernel. ## Test it The `Makefile` in this tutorial has an additional target, `qemuasm`, that lets you nicely observe how the kernel, after relocating itself, jumps the load address region (`0x80_XXX`) to the relocated code at (`0x0200_0XXX`): ```console $ make qemuasm [...] N: 0x00080030: 58000140 ldr x0, #0x80058 0x00080034: 9100001f mov sp, x0 0x00080038: 58000141 ldr x1, #0x80060 0x0008003c: d61f0020 br x1 ---------------- IN: 0x02000070: 9400044c bl #0x20011a0 ---------------- IN: 0x020011a0: 90000008 adrp x8, #0x2001000 0x020011a4: 90000009 adrp x9, #0x2001000 0x020011a8: f9446508 ldr x8, [x8, #0x8c8] 0x020011ac: f9446929 ldr x9, [x9, #0x8d0] 0x020011b0: eb08013f cmp x9, x8 0x020011b4: 54000109 b.ls #0x20011d4 [...] ``` ## Diff to previous ```diff diff -uNr 05_drivers_gpio_uart/Cargo.toml 06_uart_chainloader/Cargo.toml --- 05_drivers_gpio_uart/Cargo.toml +++ 06_uart_chainloader/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.5.0" +version = "0.6.0" authors = ["Andre Richter "] edition = "2021" Binary files 05_drivers_gpio_uart/demo_payload_rpi3.img and 06_uart_chainloader/demo_payload_rpi3.img differ Binary files 05_drivers_gpio_uart/demo_payload_rpi4.img and 06_uart_chainloader/demo_payload_rpi4.img differ diff -uNr 05_drivers_gpio_uart/Makefile 06_uart_chainloader/Makefile --- 05_drivers_gpio_uart/Makefile +++ 06_uart_chainloader/Makefile @@ -24,27 +24,29 @@ QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - READELF_BINARY = aarch64-none-elf-readelf - LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 + CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - READELF_BINARY = aarch64-none-elf-readelf - LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 + CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img endif # Export for build.rs. @@ -90,8 +92,8 @@ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb -EXEC_MINITERM = ruby ../common/serial/miniterm.rb +EXEC_TEST_MINIPUSH = ruby tests/chainboot_test.rb +EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization @@ -110,7 +112,7 @@ ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) - DOCKER_MINITERM = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) endif @@ -118,7 +120,7 @@ ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- -.PHONY: all doc qemu miniterm clippy clean readelf objdump nm check +.PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) @@ -160,7 +162,7 @@ ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. -qemu: +qemu qemuasm: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. @@ -169,13 +171,17 @@ $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) +qemuasm: $(KERNEL_BIN) + $(call color_header, "Launching QEMU with ASM output") + @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm + endif ##------------------------------------------------------------------------------ -## Connect to the target's serial +## Push the kernel to the real HW target ##------------------------------------------------------------------------------ -miniterm: - @$(DOCKER_MINITERM) $(EXEC_MINITERM) $(DEV_SERIAL) +chainboot: $(KERNEL_BIN) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) ##------------------------------------------------------------------------------ ## Run clippy @@ -232,7 +238,8 @@ ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") - @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) + @$(DOCKER_TEST) $(EXEC_TEST_MINIPUSH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) \ + -kernel $(KERNEL_BIN) $(CHAINBOOT_DEMO_PAYLOAD) test: test_boot diff -uNr 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s --- 05_drivers_gpio_uart/src/_arch/aarch64/cpu/boot.s +++ 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s @@ -18,6 +18,17 @@ add \register, \register, #:lo12:\symbol .endm +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g2:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -37,23 +48,35 @@ // If execution reaches here, it is the boot core. // Initialize DRAM. - ADR_REL x0, __bss_start - ADR_REL x1, __bss_end_exclusive + ADR_ABS x0, __bss_start + ADR_ABS x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 - b.eq .L_prepare_rust + b.eq .L_relocate_binary stp xzr, xzr, [x0], #16 b .L_bss_init_loop + // Next, relocate the binary. +.L_relocate_binary: + ADR_REL x0, __binary_nonzero_start // The address the binary got loaded to. + ADR_ABS x1, __binary_nonzero_start // The address the binary was linked to. + ADR_ABS x2, __binary_nonzero_end_exclusive + +.L_copy_loop: + ldr x3, [x0], #8 + str x3, [x1], #8 + cmp x1, x2 + b.lo .L_copy_loop + // Prepare the jump to Rust code. -.L_prepare_rust: // Set the stack pointer. - ADR_REL x0, __boot_core_stack_end_exclusive + ADR_ABS x0, __boot_core_stack_end_exclusive mov sp, x0 - // Jump to Rust code. - b _start_rust + // Jump to the relocated Rust code. + ADR_ABS x1, _start_rust + br x1 // Infinitely wait for events (aka "park the core"). .L_parking_loop: diff -uNr 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs --- 05_drivers_gpio_uart/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -275,7 +275,7 @@ } /// Retrieve a character. - fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { + fn read_char(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. @@ -290,12 +290,7 @@ } // Read one character. - let mut ret = self.registers.DR.get() as u8 as char; - - // Convert carrige return to newline. - if ret == '\r' { - ret = '\n' - } + let ret = self.registers.DR.get() as u8 as char; // Update statistics. self.chars_read += 1; @@ -381,14 +376,14 @@ impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner - .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) + .lock(|inner| inner.read_char(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner - .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) + .lock(|inner| inner.read_char(BlockingMode::NonBlocking)) .is_some() {} } diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs 06_uart_chainloader/src/bsp/raspberrypi/console.rs --- 05_drivers_gpio_uart/src/bsp/raspberrypi/console.rs +++ 06_uart_chainloader/src/bsp/raspberrypi/console.rs @@ -1,16 +0,0 @@ -// SPDX-License-Identifier: MIT OR Apache-2.0 -// -// Copyright (c) 2018-2023 Andre Richter - -//! BSP console facilities. - -use crate::console; - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// Return a reference to the console. -pub fn console() -> &'static dyn console::interface::All { - &super::driver::PL011_UART -} diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld --- 05_drivers_gpio_uart/src/bsp/raspberrypi/kernel.ld +++ 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld @@ -3,8 +3,6 @@ * Copyright (c) 2018-2023 Andre Richter */ -__rpi_phys_dram_start_addr = 0; - /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; @@ -28,7 +26,8 @@ SECTIONS { - . = __rpi_phys_dram_start_addr; + /* Set the link address to 32 MiB */ + . = 0x2000000; /*********************************************************************************************** * Boot Core Stack @@ -45,6 +44,7 @@ /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ + __binary_nonzero_start = .; .text : { KEEP(*(.text._start)) @@ -60,6 +60,10 @@ ***********************************************************************************************/ .data : { *(.data*) } :segment_data + /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ + . = ALIGN(8); + __binary_nonzero_end_exclusive = .; + /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { diff -uNr 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs 06_uart_chainloader/src/bsp/raspberrypi/memory.rs --- 05_drivers_gpio_uart/src/bsp/raspberrypi/memory.rs +++ 06_uart_chainloader/src/bsp/raspberrypi/memory.rs @@ -11,6 +11,7 @@ /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { + pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; @@ -35,3 +36,13 @@ pub const PL011_UART_START: usize = START + UART_OFFSET; } } + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The address on which the Raspberry firmware loads every binary by default. +#[inline(always)] +pub fn board_default_load_addr() -> *const u64 { + map::BOARD_DEFAULT_LOAD_ADDRESS as _ +} diff -uNr 05_drivers_gpio_uart/src/driver.rs 06_uart_chainloader/src/driver.rs --- 05_drivers_gpio_uart/src/driver.rs +++ 06_uart_chainloader/src/driver.rs @@ -4,10 +4,7 @@ //! Driver support. -use crate::{ - println, - synchronization::{interface::Mutex, NullLock}, -}; +use crate::synchronization::{interface::Mutex, NullLock}; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -154,14 +151,4 @@ } }); } - - /// Enumerate all registered device drivers. - pub fn enumerate(&self) { - let mut i: usize = 1; - self.for_each_descriptor(|descriptor| { - println!(" {}. {}", i, descriptor.device_driver.compatible()); - - i += 1; - }); - } } diff -uNr 05_drivers_gpio_uart/src/main.rs 06_uart_chainloader/src/main.rs --- 05_drivers_gpio_uart/src/main.rs +++ 06_uart_chainloader/src/main.rs @@ -142,27 +142,55 @@ kernel_main() } +const MINILOAD_LOGO: &str = r#" + __ __ _ _ _ _ +| \/ (_)_ _ (_) | ___ __ _ __| | +| |\/| | | ' \| | |__/ _ \/ _` / _` | +|_| |_|_|_||_|_|____\___/\__,_\__,_| +"#; + /// The main function running after the early init. fn kernel_main() -> ! { use console::console; - println!( - "[0] {} version {}", - env!("CARGO_PKG_NAME"), - env!("CARGO_PKG_VERSION") - ); - println!("[1] Booting on: {}", bsp::board_name()); + println!("{}", MINILOAD_LOGO); + println!("{:^37}", bsp::board_name()); + println!(); + println!("[ML] Requesting binary"); + console().flush(); - println!("[2] Drivers loaded:"); - driver::driver_manager().enumerate(); + // Discard any spurious received characters before starting with the loader protocol. + console().clear_rx(); - println!("[3] Chars written: {}", console().chars_written()); - println!("[4] Echoing input now"); + // Notify `Minipush` to send the binary. + for _ in 0..3 { + console().write_char(3 as char); + } - // Discard any spurious received characters before going into echo mode. - console().clear_rx(); - loop { - let c = console().read_char(); - console().write_char(c); + // Read the binary's size. + let mut size: u32 = u32::from(console().read_char() as u8); + size |= u32::from(console().read_char() as u8) << 8; + size |= u32::from(console().read_char() as u8) << 16; + size |= u32::from(console().read_char() as u8) << 24; + + // Trust it's not too big. + console().write_char('O'); + console().write_char('K'); + + let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; + unsafe { + // Read the kernel byte by byte. + for i in 0..size { + core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) + } } + + println!("[ML] Loaded! Executing the payload now\n"); + console().flush(); + + // Use black magic to create a function pointer. + let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; + + // Jump to loaded kernel! + kernel() } diff -uNr 05_drivers_gpio_uart/tests/boot_test_string.rb 06_uart_chainloader/tests/boot_test_string.rb --- 05_drivers_gpio_uart/tests/boot_test_string.rb +++ 06_uart_chainloader/tests/boot_test_string.rb @@ -1,3 +0,0 @@ -# frozen_string_literal: true - -EXPECTED_PRINT = 'Echoing input now' diff -uNr 05_drivers_gpio_uart/tests/chainboot_test.rb 06_uart_chainloader/tests/chainboot_test.rb --- 05_drivers_gpio_uart/tests/chainboot_test.rb +++ 06_uart_chainloader/tests/chainboot_test.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2020-2023 Andre Richter + +require_relative '../../common/serial/minipush' +require_relative '../../common/tests/boot_test' +require 'pty' + +# Match for the last print that 'demo_payload_rpiX.img' produces. +EXPECTED_PRINT = 'Echoing input now' + +# Wait for request to power the target. +class PowerTargetRequestTest < SubtestBase + MINIPUSH_POWER_TARGET_REQUEST = 'Please power the target now' + + def initialize(qemu_cmd, pty_main) + super() + @qemu_cmd = qemu_cmd + @pty_main = pty_main + end + + def name + 'Waiting for request to power target' + end + + def run(qemu_out, _qemu_in) + expect_or_raise(qemu_out, MINIPUSH_POWER_TARGET_REQUEST) + + # Now is the time to start QEMU with the chainloader binary. QEMU's virtual tty connects to + # the MiniPush instance spawned on pty_main, so that the two processes talk to each other. + Process.spawn(@qemu_cmd, in: @pty_main, out: @pty_main, err: '/dev/null') + end +end + +# Extend BootTest so that it listens on the output of a MiniPush instance, which is itself connected +# to a QEMU instance instead of a real HW. +class ChainbootTest < BootTest + MINIPUSH = '../common/serial/minipush.rb' + + def initialize(qemu_cmd, payload_path) + super(qemu_cmd, EXPECTED_PRINT) + + @test_name = 'Boot test using Minipush' + + @payload_path = payload_path + end + + private + + # override + def setup + pty_main, pty_secondary = PTY.open + mp_out, _mp_in = PTY.spawn("ruby #{MINIPUSH} #{pty_secondary.path} #{@payload_path}") + + # The subtests (from this class and the parents) listen on @qemu_out_wrapped. Hence, point + # it to MiniPush's output. + @qemu_out_wrapped = PTYLoggerWrapper.new(mp_out, "\r\n") + + # Important: Run this subtest before the one in the parent class. + @console_subtests.prepend(PowerTargetRequestTest.new(@qemu_cmd, pty_main)) + end + + # override + def finish + super() + @test_output.map! { |x| x.gsub(/.*\r/, ' ') } + end +end + +##-------------------------------------------------------------------------------------------------- +## Execution starts here +##-------------------------------------------------------------------------------------------------- +payload_path = ARGV.pop +qemu_cmd = ARGV.join(' ') + +ChainbootTest.new(qemu_cmd, payload_path).run diff -uNr 05_drivers_gpio_uart/update.sh 06_uart_chainloader/update.sh --- 05_drivers_gpio_uart/update.sh +++ 06_uart_chainloader/update.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +cd ../05_drivers_gpio_uart +BSP=rpi4 make +cp kernel8.img ../06_uart_chainloader/demo_payload_rpi4.img +make +cp kernel8.img ../06_uart_chainloader/demo_payload_rpi3.img +rm kernel8.img ``` ================================================ FILE: 06_uart_chainloader/build.rs ================================================ 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())); } ================================================ FILE: 06_uart_chainloader/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm // Load the address of a symbol into a register, absolute. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_ABS register, symbol movz \register, #:abs_g2:\symbol movk \register, #:abs_g1_nc:\symbol movk \register, #:abs_g0_nc:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x0, MPIDR_EL1 and x0, x0, {CONST_CORE_ID_MASK} ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x0, x1 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_ABS x0, __bss_start ADR_ABS x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_relocate_binary stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Next, relocate the binary. .L_relocate_binary: ADR_REL x0, __binary_nonzero_start // The address the binary got loaded to. ADR_ABS x1, __binary_nonzero_start // The address the binary was linked to. ADR_ABS x2, __binary_nonzero_end_exclusive .L_copy_loop: ldr x3, [x0], #8 str x3, [x1], #8 cmp x1, x2 b.lo .L_copy_loop // Prepare the jump to Rust code. // Set the stack pointer. ADR_ABS x0, __boot_core_stack_end_exclusive mov sp, x0 // Jump to the relocated Rust code. ADR_ABS x1, _start_rust br x1 // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 06_uart_chainloader/src/_arch/aarch64/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural processor code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::arch_cpu use aarch64_cpu::asm; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- pub use asm::nop; /// Spin for `n` cycles. #[cfg(feature = "bsp_rpi3")] #[inline(always)] pub fn spin_for_cycles(n: usize) { for _ in 0..n { asm::nop(); } } /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { loop { asm::wfe() } } ================================================ FILE: 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::cpu; // Make an educated guess for a good delay value (Sequence described in the BCM2837 // peripherals PDF). // // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. // - The Linux 2837 GPIO driver waits 1 µs between the steps. // // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs // would the CPU be clocked at 2 GHz. const DELAY: usize = 2000; self.registers.GPPUD.write(GPPUD::PUD::Off); cpu::spin_for_cycles(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); cpu::spin_for_cycles(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let ret = self.registers.DR.get() as u8 as char; // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 06_uart_chainloader/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 06_uart_chainloader/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 06_uart_chainloader/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 06_uart_chainloader/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 06_uart_chainloader/src/bsp/raspberrypi/driver.rs ================================================ // 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(()) } ================================================ FILE: 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW * * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. * It doesn't mean all of them need actually be loaded. */ PHDRS { segment_boot_core_stack PT_LOAD FLAGS(6); segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); } SECTIONS { /* Set the link address to 32 MiB */ . = 0x2000000; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : { /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __binary_nonzero_start = .; .text : { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ *(.text._start_rust) /* The Rust entry point */ *(.text*) /* Everything else */ } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ .data : { *(.data*) } :segment_data /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ . = ALIGN(8); __binary_nonzero_end_exclusive = .; /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { __bss_start = .; *(.bss*); . = ALIGN(16); __bss_end_exclusive = .; } :segment_data /*********************************************************************************************** * Misc ***********************************************************************************************/ .got : { *(.got*) } ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") /DISCARD/ : { *(.comment*) } } ================================================ FILE: 06_uart_chainloader/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The address on which the Raspberry firmware loads every binary by default. #[inline(always)] pub fn board_default_load_addr() -> *const u64 { map::BOARD_DEFAULT_LOAD_ADDRESS as _ } ================================================ FILE: 06_uart_chainloader/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 06_uart_chainloader/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 06_uart_chainloader/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 06_uart_chainloader/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 06_uart_chainloader/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 06_uart_chainloader/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; #[cfg(feature = "bsp_rpi3")] pub use arch_cpu::spin_for_cycles; ================================================ FILE: 06_uart_chainloader/src/driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Driver support. use crate::synchronization::{interface::Mutex, NullLock}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- const NUM_DRIVERS: usize = 5; struct DriverManagerInner { next_index: usize, descriptors: [Option; NUM_DRIVERS], } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Driver interfaces. pub mod interface { /// Device Driver functions. pub trait DeviceDriver { /// Return a compatibility string for identifying the driver. fn compatible(&self) -> &'static str; /// Called by the kernel to bring up the device. /// /// # Safety /// /// - During init, drivers might do stuff with system-wide impact. unsafe fn init(&self) -> Result<(), &'static str> { Ok(()) } } } /// Tpye to be used as an optional callback after a driver's init() has run. pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; /// A descriptor for device drivers. #[derive(Copy, Clone)] pub struct DeviceDriverDescriptor { device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, } /// Provides device driver management functions. pub struct DriverManager { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static DRIVER_MANAGER: DriverManager = DriverManager::new(); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl DriverManagerInner { /// Create an instance. pub const fn new() -> Self { Self { next_index: 0, descriptors: [None; NUM_DRIVERS], } } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl DeviceDriverDescriptor { /// Create an instance. pub fn new( device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, ) -> Self { Self { device_driver, post_init_callback, } } } /// Return a reference to the global DriverManager. pub fn driver_manager() -> &'static DriverManager { &DRIVER_MANAGER } impl DriverManager { /// Create an instance. pub const fn new() -> Self { Self { inner: NullLock::new(DriverManagerInner::new()), } } /// Register a device driver with the kernel. pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { self.inner.lock(|inner| { inner.descriptors[inner.next_index] = Some(descriptor); inner.next_index += 1; }) } /// Helper for iterating over registered drivers. fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { self.inner.lock(|inner| { inner .descriptors .iter() .filter_map(|x| x.as_ref()) .for_each(f) }) } /// Fully initialize all drivers. /// /// # Safety /// /// - During init, drivers might do stuff with system-wide impact. pub unsafe fn init_drivers(&self) { self.for_each_descriptor(|descriptor| { // 1. Initialize driver. if let Err(x) = descriptor.device_driver.init() { panic!( "Error initializing driver: {}: {}", descriptor.device_driver.compatible(), x ); } // 2. Call corresponding post init callback. if let Some(callback) = &descriptor.post_init_callback { if let Err(x) = callback() { panic!( "Error during driver post-init callback: {}: {}", descriptor.device_driver.compatible(), x ); } } }); } } ================================================ FILE: 06_uart_chainloader/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] #![feature(format_args_nl)] #![feature(panic_info_message)] #![feature(trait_alias)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod driver; mod panic_wait; mod print; mod synchronization; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } const MINILOAD_LOGO: &str = r#" __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| "#; /// The main function running after the early init. fn kernel_main() -> ! { use console::console; println!("{}", MINILOAD_LOGO); println!("{:^37}", bsp::board_name()); println!(); println!("[ML] Requesting binary"); console().flush(); // Discard any spurious received characters before starting with the loader protocol. console().clear_rx(); // Notify `Minipush` to send the binary. for _ in 0..3 { console().write_char(3 as char); } // Read the binary's size. let mut size: u32 = u32::from(console().read_char() as u8); size |= u32::from(console().read_char() as u8) << 8; size |= u32::from(console().read_char() as u8) << 16; size |= u32::from(console().read_char() as u8) << 24; // Trust it's not too big. console().write_char('O'); console().write_char('K'); let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; unsafe { // Read the kernel byte by byte. for i in 0..size { core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) } } println!("[ML] Loaded! Executing the payload now\n"); console().flush(); // Use black magic to create a function pointer. let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; // Jump to loaded kernel! kernel() } ================================================ FILE: 06_uart_chainloader/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 06_uart_chainloader/src/print.rs ================================================ // 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)*)); }) } ================================================ FILE: 06_uart_chainloader/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 06_uart_chainloader/tests/chainboot_test.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2020-2023 Andre Richter require_relative '../../common/serial/minipush' require_relative '../../common/tests/boot_test' require 'pty' # Match for the last print that 'demo_payload_rpiX.img' produces. EXPECTED_PRINT = 'Echoing input now' # Wait for request to power the target. class PowerTargetRequestTest < SubtestBase MINIPUSH_POWER_TARGET_REQUEST = 'Please power the target now' def initialize(qemu_cmd, pty_main) super() @qemu_cmd = qemu_cmd @pty_main = pty_main end def name 'Waiting for request to power target' end def run(qemu_out, _qemu_in) expect_or_raise(qemu_out, MINIPUSH_POWER_TARGET_REQUEST) # Now is the time to start QEMU with the chainloader binary. QEMU's virtual tty connects to # the MiniPush instance spawned on pty_main, so that the two processes talk to each other. Process.spawn(@qemu_cmd, in: @pty_main, out: @pty_main, err: '/dev/null') end end # Extend BootTest so that it listens on the output of a MiniPush instance, which is itself connected # to a QEMU instance instead of a real HW. class ChainbootTest < BootTest MINIPUSH = '../common/serial/minipush.rb' def initialize(qemu_cmd, payload_path) super(qemu_cmd, EXPECTED_PRINT) @test_name = 'Boot test using Minipush' @payload_path = payload_path end private # override def setup pty_main, pty_secondary = PTY.open mp_out, _mp_in = PTY.spawn("ruby #{MINIPUSH} #{pty_secondary.path} #{@payload_path}") # The subtests (from this class and the parents) listen on @qemu_out_wrapped. Hence, point # it to MiniPush's output. @qemu_out_wrapped = PTYLoggerWrapper.new(mp_out, "\r\n") # Important: Run this subtest before the one in the parent class. @console_subtests.prepend(PowerTargetRequestTest.new(@qemu_cmd, pty_main)) end # override def finish super() @test_output.map! { |x| x.gsub(/.*\r/, ' ') } end end ## ------------------------------------------------------------------------------------------------- ## Execution starts here ## ------------------------------------------------------------------------------------------------- payload_path = ARGV.pop qemu_cmd = ARGV.join(' ') ChainbootTest.new(qemu_cmd, payload_path).run ================================================ FILE: 06_uart_chainloader/update.sh ================================================ #!/usr/bin/env bash cd ../05_drivers_gpio_uart BSP=rpi4 make cp kernel8.img ../06_uart_chainloader/demo_payload_rpi4.img make cp kernel8.img ../06_uart_chainloader/demo_payload_rpi3.img rm kernel8.img ================================================ FILE: 07_timestamps/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 07_timestamps/Cargo.toml ================================================ [package] name = "mingo" version = "0.7.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 07_timestamps/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DEV = --privileged -v /dev:/dev # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 07_timestamps/README.CN.md ================================================ # 教程 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),这是最新的。 ================================================ FILE: 07_timestamps/README.md ================================================ # Tutorial 07 - Timestamps ## tl;dr - We add abstractions for timer hardware, and implement them for the ARM architectural timer in `_arch/aarch64`. - The new timer functions are used to annotate UART prints with timestamps, and to get rid of the cycle-based delays in the `GPIO` device driver, which boosts accuracy. - A `warn!()` macro is added. ## Test it Check it out via chainboot (added in previous tutorial): ```console $ make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 12 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.143123] mingo version 0.7.0 [ 0.143323] Booting on: Raspberry Pi 3 [ 0.143778] Architectural timer resolution: 52 ns [ 0.144352] Drivers loaded: [ 0.144688] 1. BCM PL011 UART [ 0.145110] 2. BCM GPIO [W 0.145469] Spin duration smaller than architecturally supported, skipping [ 0.146313] Spinning for 1 second [ 1.146715] Spinning for 1 second [ 2.146938] Spinning for 1 second ``` ## Diff to previous ```diff diff -uNr 06_uart_chainloader/Cargo.toml 07_timestamps/Cargo.toml --- 06_uart_chainloader/Cargo.toml +++ 07_timestamps/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.6.0" +version = "0.7.0" authors = ["Andre Richter "] edition = "2021" Binary files 06_uart_chainloader/demo_payload_rpi3.img and 07_timestamps/demo_payload_rpi3.img differ Binary files 06_uart_chainloader/demo_payload_rpi4.img and 07_timestamps/demo_payload_rpi4.img differ diff -uNr 06_uart_chainloader/Makefile 07_timestamps/Makefile --- 06_uart_chainloader/Makefile +++ 07_timestamps/Makefile @@ -24,29 +24,27 @@ QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = raspi3 - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - READELF_BINARY = aarch64-none-elf-readelf - LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi - RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 - CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi3.img + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = raspi3 + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) - TARGET = aarch64-unknown-none-softfloat - KERNEL_BIN = kernel8.img - QEMU_BINARY = qemu-system-aarch64 - QEMU_MACHINE_TYPE = - QEMU_RELEASE_ARGS = -serial stdio -display none - OBJDUMP_BINARY = aarch64-none-elf-objdump - NM_BINARY = aarch64-none-elf-nm - READELF_BINARY = aarch64-none-elf-readelf - LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi - RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 - CHAINBOOT_DEMO_PAYLOAD = demo_payload_rpi4.img + TARGET = aarch64-unknown-none-softfloat + KERNEL_BIN = kernel8.img + QEMU_BINARY = qemu-system-aarch64 + QEMU_MACHINE_TYPE = + QEMU_RELEASE_ARGS = -serial stdio -display none + OBJDUMP_BINARY = aarch64-none-elf-objdump + NM_BINARY = aarch64-none-elf-nm + READELF_BINARY = aarch64-none-elf-readelf + LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi + RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. @@ -92,7 +90,7 @@ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) -EXEC_TEST_MINIPUSH = ruby tests/chainboot_test.rb +EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ @@ -162,7 +160,7 @@ ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. -qemu qemuasm: +qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. @@ -171,17 +169,13 @@ $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -qemuasm: $(KERNEL_BIN) - $(call color_header, "Launching QEMU with ASM output") - @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) -d in_asm - endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) - @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(CHAINBOOT_DEMO_PAYLOAD) + @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy @@ -238,8 +232,7 @@ ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") - @$(DOCKER_TEST) $(EXEC_TEST_MINIPUSH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) \ - -kernel $(KERNEL_BIN) $(CHAINBOOT_DEMO_PAYLOAD) + @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot diff -uNr 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s 07_timestamps/src/_arch/aarch64/cpu/boot.s --- 06_uart_chainloader/src/_arch/aarch64/cpu/boot.s +++ 07_timestamps/src/_arch/aarch64/cpu/boot.s @@ -18,17 +18,6 @@ add \register, \register, #:lo12:\symbol .endm -// Load the address of a symbol into a register, absolute. -// -// # Resources -// -// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html -.macro ADR_ABS register, symbol - movz \register, #:abs_g2:\symbol - movk \register, #:abs_g1_nc:\symbol - movk \register, #:abs_g0_nc:\symbol -.endm - //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -48,35 +37,31 @@ // If execution reaches here, it is the boot core. // Initialize DRAM. - ADR_ABS x0, __bss_start - ADR_ABS x1, __bss_end_exclusive + ADR_REL x0, __bss_start + ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 - b.eq .L_relocate_binary + b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop - // Next, relocate the binary. -.L_relocate_binary: - ADR_REL x0, __binary_nonzero_start // The address the binary got loaded to. - ADR_ABS x1, __binary_nonzero_start // The address the binary was linked to. - ADR_ABS x2, __binary_nonzero_end_exclusive - -.L_copy_loop: - ldr x3, [x0], #8 - str x3, [x1], #8 - cmp x1, x2 - b.lo .L_copy_loop - // Prepare the jump to Rust code. +.L_prepare_rust: // Set the stack pointer. - ADR_ABS x0, __boot_core_stack_end_exclusive + ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 - // Jump to the relocated Rust code. - ADR_ABS x1, _start_rust - br x1 + // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. + // Abort if the frequency read back as 0. + ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x2, CNTFRQ_EL0 + cmp x2, xzr + b.eq .L_parking_loop + str w2, [x1] + + // Jump to Rust code. + b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: diff -uNr 06_uart_chainloader/src/_arch/aarch64/cpu.rs 07_timestamps/src/_arch/aarch64/cpu.rs --- 06_uart_chainloader/src/_arch/aarch64/cpu.rs +++ 07_timestamps/src/_arch/aarch64/cpu.rs @@ -19,15 +19,6 @@ pub use asm::nop; -/// Spin for `n` cycles. -#[cfg(feature = "bsp_rpi3")] -#[inline(always)] -pub fn spin_for_cycles(n: usize) { - for _ in 0..n { - asm::nop(); - } -} - /// Pause execution on the core. #[inline(always)] pub fn wait_forever() -> ! { diff -uNr 06_uart_chainloader/src/_arch/aarch64/time.rs 07_timestamps/src/_arch/aarch64/time.rs --- 06_uart_chainloader/src/_arch/aarch64/time.rs +++ 07_timestamps/src/_arch/aarch64/time.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural timer primitives. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::time::arch_time + +use crate::warn; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{ + num::{NonZeroU128, NonZeroU32, NonZeroU64}, + ops::{Add, Div}, + time::Duration, +}; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +const NANOSEC_PER_SEC: NonZeroU64 = NonZeroU64::new(1_000_000_000).unwrap(); + +#[derive(Copy, Clone, PartialOrd, PartialEq)] +struct GenericTimerCounterValue(u64); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// Boot assembly code overwrites this value with the value of CNTFRQ_EL0 before any Rust code is +/// executed. This given value here is just a (safe) dummy. +#[no_mangle] +static ARCH_TIMER_COUNTER_FREQUENCY: NonZeroU32 = NonZeroU32::MIN; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn arch_timer_counter_frequency() -> NonZeroU32 { + // Read volatile is needed here to prevent the compiler from optimizing + // ARCH_TIMER_COUNTER_FREQUENCY away. + // + // This is safe, because all the safety requirements as stated in read_volatile()'s + // documentation are fulfilled. + unsafe { core::ptr::read_volatile(&ARCH_TIMER_COUNTER_FREQUENCY) } +} + +impl GenericTimerCounterValue { + pub const MAX: Self = GenericTimerCounterValue(u64::MAX); +} + +impl Add for GenericTimerCounterValue { + type Output = Self; + + fn add(self, other: Self) -> Self { + GenericTimerCounterValue(self.0.wrapping_add(other.0)) + } +} + +impl From for Duration { + fn from(counter_value: GenericTimerCounterValue) -> Self { + if counter_value.0 == 0 { + return Duration::ZERO; + } + + let frequency: NonZeroU64 = arch_timer_counter_frequency().into(); + + // Div implementation for u64 cannot panic. + let secs = counter_value.0.div(frequency); + + // This is safe, because frequency can never be greater than u32::MAX, which means the + // largest theoretical value for sub_second_counter_value is (u32::MAX - 1). Therefore, + // (sub_second_counter_value * NANOSEC_PER_SEC) cannot overflow an u64. + // + // The subsequent division ensures the result fits into u32, since the max result is smaller + // than NANOSEC_PER_SEC. Therefore, just cast it to u32 using `as`. + let sub_second_counter_value = counter_value.0 modulo frequency; + let nanos = unsafe { sub_second_counter_value.unchecked_mul(u64::from(NANOSEC_PER_SEC)) } + .div(frequency) as u32; + + Duration::new(secs, nanos) + } +} + +fn max_duration() -> Duration { + Duration::from(GenericTimerCounterValue::MAX) +} + +impl TryFrom for GenericTimerCounterValue { + type Error = &'static str; + + fn try_from(duration: Duration) -> Result { + if duration < resolution() { + return Ok(GenericTimerCounterValue(0)); + } + + if duration > max_duration() { + return Err("Conversion error. Duration too big"); + } + + let frequency: u128 = u32::from(arch_timer_counter_frequency()) as u128; + let duration: u128 = duration.as_nanos(); + + // This is safe, because frequency can never be greater than u32::MAX, and + // (Duration::MAX.as_nanos() * u32::MAX) < u128::MAX. + let counter_value = + unsafe { duration.unchecked_mul(frequency) }.div(NonZeroU128::from(NANOSEC_PER_SEC)); + + // Since we checked above that we are <= max_duration(), just cast to u64. + Ok(GenericTimerCounterValue(counter_value as u64)) + } +} + +#[inline(always)] +fn read_cntpct() -> GenericTimerCounterValue { + // Prevent that the counter is read ahead of time due to out-of-order execution. + barrier::isb(barrier::SY); + let cnt = CNTPCT_EL0.get(); + + GenericTimerCounterValue(cnt) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// The timer's resolution. +pub fn resolution() -> Duration { + Duration::from(GenericTimerCounterValue(1)) +} + +/// The uptime since power-on of the device. +/// +/// This includes time consumed by firmware and bootloaders. +pub fn uptime() -> Duration { + read_cntpct().into() +} + +/// Spin for a given duration. +pub fn spin_for(duration: Duration) { + let curr_counter_value = read_cntpct(); + + let counter_value_delta: GenericTimerCounterValue = match duration.try_into() { + Err(msg) => { + warn!("spin_for: {}. Skipping", msg); + return; + } + Ok(val) => val, + }; + let counter_value_target = curr_counter_value + counter_value_delta; + + // Busy wait. + // + // Read CNTPCT_EL0 directly to avoid the ISB that is part of [`read_cntpct`]. + while GenericTimerCounterValue(CNTPCT_EL0.get()) < counter_value_target {} +} diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs --- 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -140,25 +140,19 @@ /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { - use crate::cpu; + use crate::time; + use core::time::Duration; - // Make an educated guess for a good delay value (Sequence described in the BCM2837 - // peripherals PDF). - // - // - According to Wikipedia, the fastest RPi4 clocks around 1.5 GHz. - // - The Linux 2837 GPIO driver waits 1 µs between the steps. - // - // So lets try to be on the safe side and default to 2000 cycles, which would equal 1 µs - // would the CPU be clocked at 2 GHz. - const DELAY: usize = 2000; + // The Linux 2837 GPIO driver waits 1 µs between the steps. + const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); - cpu::spin_for_cycles(DELAY); + time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); - cpu::spin_for_cycles(DELAY); + time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); diff -uNr 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs --- 06_uart_chainloader/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -275,7 +275,7 @@ } /// Retrieve a character. - fn read_char(&mut self, blocking_mode: BlockingMode) -> Option { + fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. @@ -290,7 +290,12 @@ } // Read one character. - let ret = self.registers.DR.get() as u8 as char; + let mut ret = self.registers.DR.get() as u8 as char; + + // Convert carrige return to newline. + if ret == '\r' { + ret = '\n' + } // Update statistics. self.chars_read += 1; @@ -376,14 +381,14 @@ impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner - .lock(|inner| inner.read_char(BlockingMode::Blocking).unwrap()) + .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner - .lock(|inner| inner.read_char(BlockingMode::NonBlocking)) + .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/driver.rs 07_timestamps/src/bsp/raspberrypi/driver.rs --- 06_uart_chainloader/src/bsp/raspberrypi/driver.rs +++ 07_timestamps/src/bsp/raspberrypi/driver.rs @@ -57,6 +57,17 @@ /// # Safety /// /// See child function calls. +/// +/// # Note +/// +/// Using atomics here relieves us from needing to use `unsafe` for the static variable. +/// +/// On `AArch64`, which is the only implemented architecture at the time of writing this, +/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store +/// instructions. They are therefore safe to use even with MMU + caching deactivated. +/// +/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load +/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store pub unsafe fn init() -> Result<(), &'static str> { static INIT_DONE: AtomicBool = AtomicBool::new(false); if INIT_DONE.load(Ordering::Relaxed) { diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld 07_timestamps/src/bsp/raspberrypi/kernel.ld --- 06_uart_chainloader/src/bsp/raspberrypi/kernel.ld +++ 07_timestamps/src/bsp/raspberrypi/kernel.ld @@ -3,6 +3,8 @@ * Copyright (c) 2018-2023 Andre Richter */ +__rpi_phys_dram_start_addr = 0; + /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; @@ -26,8 +28,7 @@ SECTIONS { - /* Set the link address to 32 MiB */ - . = 0x2000000; + . = __rpi_phys_dram_start_addr; /*********************************************************************************************** * Boot Core Stack @@ -44,7 +45,6 @@ /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ - __binary_nonzero_start = .; .text : { KEEP(*(.text._start)) @@ -60,10 +60,6 @@ ***********************************************************************************************/ .data : { *(.data*) } :segment_data - /* Fill up to 8 byte, b/c relocating the binary is done in u64 chunks */ - . = ALIGN(8); - __binary_nonzero_end_exclusive = .; - /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { diff -uNr 06_uart_chainloader/src/bsp/raspberrypi/memory.rs 07_timestamps/src/bsp/raspberrypi/memory.rs --- 06_uart_chainloader/src/bsp/raspberrypi/memory.rs +++ 07_timestamps/src/bsp/raspberrypi/memory.rs @@ -11,7 +11,6 @@ /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { - pub const BOARD_DEFAULT_LOAD_ADDRESS: usize = 0x8_0000; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; @@ -36,13 +35,3 @@ pub const PL011_UART_START: usize = START + UART_OFFSET; } } - -//-------------------------------------------------------------------------------------------------- -// Public Code -//-------------------------------------------------------------------------------------------------- - -/// The address on which the Raspberry firmware loads every binary by default. -#[inline(always)] -pub fn board_default_load_addr() -> *const u64 { - map::BOARD_DEFAULT_LOAD_ADDRESS as _ -} diff -uNr 06_uart_chainloader/src/cpu.rs 07_timestamps/src/cpu.rs --- 06_uart_chainloader/src/cpu.rs +++ 07_timestamps/src/cpu.rs @@ -14,6 +14,3 @@ // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; - -#[cfg(feature = "bsp_rpi3")] -pub use arch_cpu::spin_for_cycles; diff -uNr 06_uart_chainloader/src/driver.rs 07_timestamps/src/driver.rs --- 06_uart_chainloader/src/driver.rs +++ 07_timestamps/src/driver.rs @@ -4,7 +4,10 @@ //! Driver support. -use crate::synchronization::{interface::Mutex, NullLock}; +use crate::{ + info, + synchronization::{interface::Mutex, NullLock}, +}; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -151,4 +154,14 @@ } }); } + + /// Enumerate all registered device drivers. + pub fn enumerate(&self) { + let mut i: usize = 1; + self.for_each_descriptor(|descriptor| { + info!(" {}. {}", i, descriptor.device_driver.compatible()); + + i += 1; + }); + } } diff -uNr 06_uart_chainloader/src/main.rs 07_timestamps/src/main.rs --- 06_uart_chainloader/src/main.rs +++ 07_timestamps/src/main.rs @@ -108,9 +108,12 @@ #![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] +#![feature(const_option)] #![feature(format_args_nl)] +#![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] +#![feature(unchecked_math)] #![no_main] #![no_std] @@ -121,6 +124,7 @@ mod panic_wait; mod print; mod synchronization; +mod time; /// Early init code. /// @@ -142,55 +146,30 @@ kernel_main() } -const MINILOAD_LOGO: &str = r#" - __ __ _ _ _ _ -| \/ (_)_ _ (_) | ___ __ _ __| | -| |\/| | | ' \| | |__/ _ \/ _` / _` | -|_| |_|_|_||_|_|____\___/\__,_\__,_| -"#; - /// The main function running after the early init. fn kernel_main() -> ! { - use console::console; - - println!("{}", MINILOAD_LOGO); - println!("{:^37}", bsp::board_name()); - println!(); - println!("[ML] Requesting binary"); - console().flush(); - - // Discard any spurious received characters before starting with the loader protocol. - console().clear_rx(); - - // Notify `Minipush` to send the binary. - for _ in 0..3 { - console().write_char(3 as char); - } + use core::time::Duration; - // Read the binary's size. - let mut size: u32 = u32::from(console().read_char() as u8); - size |= u32::from(console().read_char() as u8) << 8; - size |= u32::from(console().read_char() as u8) << 16; - size |= u32::from(console().read_char() as u8) << 24; - - // Trust it's not too big. - console().write_char('O'); - console().write_char('K'); - - let kernel_addr: *mut u8 = bsp::memory::board_default_load_addr() as *mut u8; - unsafe { - // Read the kernel byte by byte. - for i in 0..size { - core::ptr::write_volatile(kernel_addr.offset(i as isize), console().read_char() as u8) - } + info!( + "{} version {}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + info!("Booting on: {}", bsp::board_name()); + + info!( + "Architectural timer resolution: {} ns", + time::time_manager().resolution().as_nanos() + ); + + info!("Drivers loaded:"); + driver::driver_manager().enumerate(); + + // Test a failing timer case. + time::time_manager().spin_for(Duration::from_nanos(1)); + + loop { + info!("Spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); } - - println!("[ML] Loaded! Executing the payload now\n"); - console().flush(); - - // Use black magic to create a function pointer. - let kernel: fn() -> ! = unsafe { core::mem::transmute(kernel_addr) }; - - // Jump to loaded kernel! - kernel() } diff -uNr 06_uart_chainloader/src/panic_wait.rs 07_timestamps/src/panic_wait.rs --- 06_uart_chainloader/src/panic_wait.rs +++ 07_timestamps/src/panic_wait.rs @@ -45,15 +45,18 @@ // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); + let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( - "Kernel panic!\n\n\ + "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", + timestamp.as_secs(), + timestamp.subsec_micros(), location, line, column, diff -uNr 06_uart_chainloader/src/print.rs 07_timestamps/src/print.rs --- 06_uart_chainloader/src/print.rs +++ 07_timestamps/src/print.rs @@ -34,3 +34,51 @@ $crate::print::_print(format_args_nl!($($arg)*)); }) } + +/// Prints an info, with a newline. +#[macro_export] +macro_rules! info { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[ {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} + +/// Prints a warning, with a newline. +#[macro_export] +macro_rules! warn { + ($string:expr) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $string), + timestamp.as_secs(), + timestamp.subsec_micros(), + )); + }); + ($format_string:expr, $($arg:tt)*) => ({ + let timestamp = $crate::time::time_manager().uptime(); + + $crate::print::_print(format_args_nl!( + concat!("[W {:>3}.{:06}] ", $format_string), + timestamp.as_secs(), + timestamp.subsec_micros(), + $($arg)* + )); + }) +} diff -uNr 06_uart_chainloader/src/time.rs 07_timestamps/src/time.rs --- 06_uart_chainloader/src/time.rs +++ 07_timestamps/src/time.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Timer primitives. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/time.rs"] +mod arch_time; + +use core::time::Duration; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Provides time management functions. +pub struct TimeManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static TIME_MANAGER: TimeManager = TimeManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global TimeManager. +pub fn time_manager() -> &'static TimeManager { + &TIME_MANAGER +} + +impl TimeManager { + /// Create an instance. + pub const fn new() -> Self { + Self + } + + /// The timer's resolution. + pub fn resolution(&self) -> Duration { + arch_time::resolution() + } + + /// The uptime since power-on of the device. + /// + /// This includes time consumed by firmware and bootloaders. + pub fn uptime(&self) -> Duration { + arch_time::uptime() + } + + /// Spin for a given duration. + pub fn spin_for(&self, duration: Duration) { + arch_time::spin_for(duration) + } +} diff -uNr 06_uart_chainloader/tests/boot_test_string.rb 07_timestamps/tests/boot_test_string.rb --- 06_uart_chainloader/tests/boot_test_string.rb +++ 07_timestamps/tests/boot_test_string.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +EXPECTED_PRINT = 'Spinning for 1 second' diff -uNr 06_uart_chainloader/tests/chainboot_test.rb 07_timestamps/tests/chainboot_test.rb --- 06_uart_chainloader/tests/chainboot_test.rb +++ 07_timestamps/tests/chainboot_test.rb @@ -1,78 +0,0 @@ -# frozen_string_literal: true - -# SPDX-License-Identifier: MIT OR Apache-2.0 -# -# Copyright (c) 2020-2023 Andre Richter - -require_relative '../../common/serial/minipush' -require_relative '../../common/tests/boot_test' -require 'pty' - -# Match for the last print that 'demo_payload_rpiX.img' produces. -EXPECTED_PRINT = 'Echoing input now' - -# Wait for request to power the target. -class PowerTargetRequestTest < SubtestBase - MINIPUSH_POWER_TARGET_REQUEST = 'Please power the target now' - - def initialize(qemu_cmd, pty_main) - super() - @qemu_cmd = qemu_cmd - @pty_main = pty_main - end - - def name - 'Waiting for request to power target' - end - - def run(qemu_out, _qemu_in) - expect_or_raise(qemu_out, MINIPUSH_POWER_TARGET_REQUEST) - - # Now is the time to start QEMU with the chainloader binary. QEMU's virtual tty connects to - # the MiniPush instance spawned on pty_main, so that the two processes talk to each other. - Process.spawn(@qemu_cmd, in: @pty_main, out: @pty_main, err: '/dev/null') - end -end - -# Extend BootTest so that it listens on the output of a MiniPush instance, which is itself connected -# to a QEMU instance instead of a real HW. -class ChainbootTest < BootTest - MINIPUSH = '../common/serial/minipush.rb' - - def initialize(qemu_cmd, payload_path) - super(qemu_cmd, EXPECTED_PRINT) - - @test_name = 'Boot test using Minipush' - - @payload_path = payload_path - end - - private - - # override - def setup - pty_main, pty_secondary = PTY.open - mp_out, _mp_in = PTY.spawn("ruby #{MINIPUSH} #{pty_secondary.path} #{@payload_path}") - - # The subtests (from this class and the parents) listen on @qemu_out_wrapped. Hence, point - # it to MiniPush's output. - @qemu_out_wrapped = PTYLoggerWrapper.new(mp_out, "\r\n") - - # Important: Run this subtest before the one in the parent class. - @console_subtests.prepend(PowerTargetRequestTest.new(@qemu_cmd, pty_main)) - end - - # override - def finish - super() - @test_output.map! { |x| x.gsub(/.*\r/, ' ') } - end -end - -##-------------------------------------------------------------------------------------------------- -## Execution starts here -##-------------------------------------------------------------------------------------------------- -payload_path = ARGV.pop -qemu_cmd = ARGV.join(' ') - -ChainbootTest.new(qemu_cmd, payload_path).run diff -uNr 06_uart_chainloader/update.sh 07_timestamps/update.sh --- 06_uart_chainloader/update.sh +++ 07_timestamps/update.sh @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -cd ../05_drivers_gpio_uart -BSP=rpi4 make -cp kernel8.img ../06_uart_chainloader/demo_payload_rpi4.img -make -cp kernel8.img ../06_uart_chainloader/demo_payload_rpi3.img -rm kernel8.img ``` ================================================ FILE: 07_timestamps/build.rs ================================================ 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())); } ================================================ FILE: 07_timestamps/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: 07_timestamps/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x0, MPIDR_EL1 and x0, x0, {CONST_CORE_ID_MASK} ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x0, x1 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 07_timestamps/src/_arch/aarch64/cpu.rs ================================================ // 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() } } ================================================ FILE: 07_timestamps/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 07_timestamps/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 07_timestamps/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 07_timestamps/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 07_timestamps/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 07_timestamps/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 07_timestamps/src/bsp/raspberrypi/driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP driver support. use super::memory::map::mmio; use crate::{bsp::device_driver, console, driver as generic_driver}; use core::sync::atomic::{AtomicBool, Ordering}; //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static PL011_UART: device_driver::PL011Uart = unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// This must be called only after successful init of the UART driver. fn post_init_uart() -> Result<(), &'static str> { console::register_console(&PL011_UART); Ok(()) } /// This must be called only after successful init of the GPIO driver. fn post_init_gpio() -> Result<(), &'static str> { GPIO.map_pl011_uart(); Ok(()) } fn driver_uart() -> Result<(), &'static str> { let uart_descriptor = generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); generic_driver::driver_manager().register_driver(uart_descriptor); Ok(()) } fn driver_gpio() -> Result<(), &'static str> { let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); generic_driver::driver_manager().register_driver(gpio_descriptor); Ok(()) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Initialize the driver subsystem. /// /// # Safety /// /// See child function calls. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store pub unsafe fn init() -> Result<(), &'static str> { static INIT_DONE: AtomicBool = AtomicBool::new(false); if INIT_DONE.load(Ordering::Relaxed) { return Err("Init already done"); } driver_uart()?; driver_gpio()?; INIT_DONE.store(true, Ordering::Relaxed); Ok(()) } ================================================ FILE: 07_timestamps/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 07_timestamps/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } } ================================================ FILE: 07_timestamps/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 07_timestamps/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 07_timestamps/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 07_timestamps/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 07_timestamps/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 07_timestamps/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; ================================================ FILE: 07_timestamps/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 07_timestamps/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] #![feature(const_option)] #![feature(format_args_nl)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod driver; mod panic_wait; mod print; mod synchronization; mod time; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { use core::time::Duration; info!( "{} version {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION") ); info!("Booting on: {}", bsp::board_name()); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); // Test a failing timer case. time::time_manager().spin_for(Duration::from_nanos(1)); loop { info!("Spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); } } ================================================ FILE: 07_timestamps/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", timestamp.as_secs(), timestamp.subsec_micros(), location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 07_timestamps/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 07_timestamps/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 07_timestamps/src/time.rs ================================================ // 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) } } ================================================ FILE: 07_timestamps/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Spinning for 1 second' ================================================ FILE: 08_hw_debug_JTAG/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 08_hw_debug_JTAG/Cargo.toml ================================================ [package] name = "mingo" version = "0.8.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 08_hw_debug_JTAG/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 08_hw_debug_JTAG/README.CN.md ================================================ # 教程 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 # Name JTAG # Note Diagram
VTREF 1 to 3.3V
GND 4 to GND
22 TRST 3
26 TDI 5
27 TMS 7
25 TCK 9
23 RTCK 11
24 TDO 13

## 准备连接 在启动时,由于我们对`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),这是最新的。 ================================================ FILE: 08_hw_debug_JTAG/README.md ================================================ # Tutorial 08 - Hardware Debugging using JTAG ## tl;dr In the exact order as listed: 1. `make jtagboot` and keep terminal open. 2. Connect USB serial device. 3. Connect `JTAG` debugger USB device. 4. In new terminal, `make openocd` and keep terminal open. 5. In new terminal, `make gdb` or make `make gdb-opt0`. ![Demo](../doc/09_demo.gif) ## Table of Contents - [Introduction](#introduction) - [Outline](#outline) - [Software Setup](#software-setup) - [Hardware Setup](#hardware-setup) * [Wiring](#wiring) - [Getting ready to connect](#getting-ready-to-connect) - [OpenOCD](#openocd) - [GDB](#gdb) * [Remarks](#remarks) + [Optimization](#optimization) + [GDB control](#gdb-control) - [Notes on USB connection constraints](#notes-on-usb-connection-constraints) - [Additional resources](#additional-resources) - [Acknowledgments](#acknowledgments) - [Diff to previous](#diff-to-previous) ## Introduction In the upcoming tutorials, we are going to touch sensitive areas of the RPi's SoC that can make our debugging life very hard. For example, changing the processor's `Privilege Level` or introducing `Virtual Memory`. A hardware based debugger can sometimes be the last resort when searching for a tricky bug. Especially for debugging intricate, architecture-specific HW issues, it will be handy, because in this area `QEMU` sometimes can not help, since it abstracts certain features of the HW and doesn't simulate down to the very last bit. So lets introduce `JTAG` debugging. Once set up, it will allow us to single-step through our kernel on the real HW. How cool is that?! ## Outline From kernel perspective, this tutorial is the same as the previous one. We are just wrapping infrastructure for JTAG debugging around it. ## Software Setup We need to add another line to the `config.txt` file from the SD Card: ```toml arm_64bit=1 init_uart_clock=48000000 enable_jtag_gpio=1 ``` ## Hardware Setup Unlike microcontroller boards like the `STM32F3DISCOVERY`, which is used in our WG's [Embedded Rust Book], the Raspberry Pi does not have an embedded debugger on its board. Hence, you need to buy one. For this tutorial, we will use the [ARM-USB-TINY-H] from OLIMEX. It has a standard [ARM JTAG 20 connector]. Unfortunately, the RPi does not, so we have to connect it via jumper wires. [Embedded Rust Book]: https://rust-embedded.github.io/book/start/hardware.html [ARM-USB-TINY-H]: https://www.olimex.com/Products/ARM/JTAG/ARM-USB-TINY-H [ARM JTAG 20 connector]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0499dj/BEHEIHCE.html ### Wiring
GPIO # Name JTAG # Note Diagram
VTREF 1 to 3.3V
GND 4 to GND
22 TRST 3
26 TDI 5
27 TMS 7
25 TCK 9
23 RTCK 11
24 TDO 13

## Getting ready to connect Upon booting, thanks to the changes we made to `config.txt`, the RPi's firmware will configure the respective GPIO pins for `JTAG` functionality. What is left to do now is to pause the execution of the RPi and then connect over `JTAG`. Therefore, we add a new `Makefile` target, `make jtagboot`, which uses the `chainboot` approach to load a tiny helper binary onto the RPi that just parks the executing core into a waiting state. The helper binary is maintained separately in this repository's [X1_JTAG_boot] folder, and is a modified version of the kernel we used in our tutorials so far. [X1_JTAG_boot]: ../X1_JTAG_boot ```console $ make jtagboot Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 7 KiB ==========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.394532] Parking CPU core. Please connect over JTAG now. ``` It is important to keep the USB serial connected and the terminal with the `jtagboot` open and running. When we load the actual kernel later, `UART` output will appear here. ## OpenOCD Next, we need to launch the [Open On-Chip Debugger], aka `OpenOCD` to actually connect the `JTAG`. [Open On-Chip Debugger]: http://openocd.org As always, our tutorials try to be as painless as possible regarding dev-tools, which is why we have packaged everything into the [dedicated Docker container] that is already used for chainbooting and `QEMU`. [dedicated Docker container]: ../docker/rustembedded-osdev-utils Connect the Olimex USB JTAG debugger, open a new terminal and in the same folder, type `make openocd` (in that order!). You will see some initial output: ```console $ make openocd [...] Open On-Chip Debugger 0.10.0 [...] Info : Listening on port 6666 for tcl connections Info : Listening on port 4444 for telnet connections Info : clock speed 1000 kHz Info : JTAG tap: rpi3.tap tap/device found: 0x4ba00477 (mfg: 0x23b (ARM Ltd.), part: 0xba00, ver: 0x4) Info : rpi3.core0: hardware has 6 breakpoints, 4 watchpoints Info : rpi3.core1: hardware has 6 breakpoints, 4 watchpoints Info : rpi3.core2: hardware has 6 breakpoints, 4 watchpoints Info : rpi3.core3: hardware has 6 breakpoints, 4 watchpoints Info : Listening on port 3333 for gdb connections Info : Listening on port 3334 for gdb connections Info : Listening on port 3335 for gdb connections Info : Listening on port 3336 for gdb connections ``` `OpenOCD` has detected the four cores of the RPi, and opened four network ports to which `gdb` can now connect to debug the respective core. ## GDB Finally, we need an `AArch64`-capable version of `gdb`. You guessed right, it's already packaged in the osdev container. It can be launched via `make gdb`. This Makefile target actually does a little more. It builds a special version of our kernel with debug information included. This enables `gdb` to show the `Rust` source code line we are currently debugging. It also launches `gdb` such that it already loads this debug build (`kernel_for_jtag`). We can now use the `gdb` commandline to 1. Set breakpoints in our kernel 2. Load the kernel via JTAG into memory (remember that currently, the RPi is still executing the minimal JTAG boot binary). 3. Manipulate the program counter of the RPi to start execution at our kernel's entry point. 4. Single-step through its execution. ```console $ make gdb [...] >>> target remote :3333 # Connect to OpenOCD, core0 >>> load # Load the kernel into the RPi's DRAM over JTAG. Loading section .text, size 0x2454 lma 0x80000 Loading section .rodata, size 0xa1d lma 0x82460 Loading section .got, size 0x10 lma 0x82e80 Loading section .data, size 0x20 lma 0x82e90 Start address 0x0000000000080000, load size 11937 Transfer rate: 63 KB/sec, 2984 bytes/write. >>> set $pc = 0x80000 # Set RPI's program counter to the start of the # kernel binary. >>> break main.rs:158 Breakpoint 1 at 0x8025c: file src/main.rs, line 158. >>> cont >>> step # Single-step through the kernel >>> step >>> ... ``` ### Remarks #### Optimization When debugging an OS binary, you have to make a trade-off between the granularity at which you can step through your Rust source-code and the optimization level of the generated binary. The `make` and `make gdb` targets produce a `--release` binary, which includes an optimization level of three (`-opt-level=3`). However, in this case, the compiler will inline very aggressively and pack together reads and writes where possible. As a result, it will not always be possible to hit breakpoints exactly where you want to regarding the line of source code file. For this reason, the Makefile also provides the `make gdb-opt0` target, which uses `-opt-level=0`. Hence, it will allow you to have finer debugging granularity. However, please keep in mind that when debugging code that closely deals with HW, a compiler optimization that squashes reads or writes to volatile registers can make all the difference in execution. FYI, the demo gif above has been recorded with `gdb-opt0`. #### GDB control At some point, you may reach delay loops or code that waits on user input from the serial. Here, single stepping might not be feasible or work anymore. You can jump over these roadblocks by setting other breakpoints beyond these areas, and reach them using the `cont` command. Pressing `ctrl+c` in `gdb` will stop execution of the RPi again in case you continued it without further breakpoints. ## Notes on USB connection constraints If you followed the tutorial from top to bottom, everything should be fine regarding USB connections. Still, please note that in its current form, our `Makefile` makes implicit assumptions about the naming of the connected USB devices. It expects `/dev/ttyUSB0` to be the `UART` device. Hence, please ensure the following order of connecting the devices to your box: 1. Connect the USB serial. 2. Afterwards, the Olimex debugger. This way, the host OS enumerates the devices accordingly. This has to be done only once. It is fine to disconnect and connect the serial multiple times, e.g. for kicking off different `make jtagboot` runs, while keeping the debugger connected. ## Additional resources - https://metebalci.com/blog/bare-metal-raspberry-pi-3b-jtag - https://www.suse.com/c/debugging-raspberry-pi-3-with-jtag ## Acknowledgments Thanks to [@naotaco](https://github.com/naotaco) for laying the groundwork for this tutorial. ## Diff to previous ```diff diff -uNr 07_timestamps/Cargo.toml 08_hw_debug_JTAG/Cargo.toml --- 07_timestamps/Cargo.toml +++ 08_hw_debug_JTAG/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.7.0" +version = "0.8.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 07_timestamps/Makefile 08_hw_debug_JTAG/Makefile --- 07_timestamps/Makefile +++ 08_hw_debug_JTAG/Makefile @@ -32,6 +32,8 @@ OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) @@ -43,6 +45,8 @@ OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf + OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg + JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif @@ -99,18 +103,25 @@ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common +DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev +DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) +DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) + DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) + DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) +else + DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif @@ -215,6 +226,35 @@ +##-------------------------------------------------------------------------------------------------- +## Debugging targets +##-------------------------------------------------------------------------------------------------- +.PHONY: jtagboot openocd gdb gdb-opt0 + +##------------------------------------------------------------------------------ +## Push the JTAG boot image to the real HW target +##------------------------------------------------------------------------------ +jtagboot: + @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) + +##------------------------------------------------------------------------------ +## Start OpenOCD session +##------------------------------------------------------------------------------ +openocd: + $(call color_header, "Launching OpenOCD") + @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) + +##------------------------------------------------------------------------------ +## Start GDB session +##------------------------------------------------------------------------------ +gdb: RUSTC_MISC_ARGS += -C debuginfo=2 +gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 +gdb gdb-opt0: $(KERNEL_ELF) + $(call color_header, "Launching GDB") + @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) + + + ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- diff -uNr 07_timestamps/src/bsp/raspberrypi/driver.rs 08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs --- 07_timestamps/src/bsp/raspberrypi/driver.rs +++ 08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs @@ -57,17 +57,6 @@ /// # Safety /// /// See child function calls. -/// -/// # Note -/// -/// Using atomics here relieves us from needing to use `unsafe` for the static variable. -/// -/// On `AArch64`, which is the only implemented architecture at the time of writing this, -/// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store -/// instructions. They are therefore safe to use even with MMU + caching deactivated. -/// -/// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load -/// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store pub unsafe fn init() -> Result<(), &'static str> { static INIT_DONE: AtomicBool = AtomicBool::new(false); if INIT_DONE.load(Ordering::Relaxed) { ``` ================================================ FILE: 08_hw_debug_JTAG/build.rs ================================================ 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())); } ================================================ FILE: 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x0, MPIDR_EL1 and x0, x0, {CONST_CORE_ID_MASK} ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x0, x1 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 08_hw_debug_JTAG/src/_arch/aarch64/cpu.rs ================================================ // 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() } } ================================================ FILE: 08_hw_debug_JTAG/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 08_hw_debug_JTAG/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 08_hw_debug_JTAG/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 08_hw_debug_JTAG/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 08_hw_debug_JTAG/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 08_hw_debug_JTAG/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 08_hw_debug_JTAG/src/bsp/raspberrypi/driver.rs ================================================ // 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(()) } ================================================ FILE: 08_hw_debug_JTAG/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 08_hw_debug_JTAG/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } } ================================================ FILE: 08_hw_debug_JTAG/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 08_hw_debug_JTAG/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 08_hw_debug_JTAG/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 08_hw_debug_JTAG/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 08_hw_debug_JTAG/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 08_hw_debug_JTAG/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; ================================================ FILE: 08_hw_debug_JTAG/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 08_hw_debug_JTAG/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] #![feature(const_option)] #![feature(format_args_nl)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod driver; mod panic_wait; mod print; mod synchronization; mod time; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { use core::time::Duration; info!( "{} version {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION") ); info!("Booting on: {}", bsp::board_name()); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); // Test a failing timer case. time::time_manager().spin_for(Duration::from_nanos(1)); loop { info!("Spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); } } ================================================ FILE: 08_hw_debug_JTAG/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", timestamp.as_secs(), timestamp.subsec_micros(), location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 08_hw_debug_JTAG/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 08_hw_debug_JTAG/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 08_hw_debug_JTAG/src/time.rs ================================================ // 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) } } ================================================ FILE: 08_hw_debug_JTAG/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Spinning for 1 second' ================================================ FILE: 09_privilege_level/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 09_privilege_level/Cargo.toml ================================================ [package] name = "mingo" version = "0.9.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 09_privilege_level/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 09_privilege_level/README.CN.md ================================================ # 教程 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),这是最新的。 ================================================ FILE: 09_privilege_level/README.md ================================================ # Tutorial 09 - Privilege Level ## tl;dr - In early boot code, we transition from the `Hypervisor` privilege level (`EL2` in AArch64) to the `Kernel` (`EL1`) privilege level. ## Table of Contents - [Introduction](#introduction) - [Scope of this tutorial](#scope-of-this-tutorial) - [Checking for EL2 in the entrypoint](#checking-for-el2-in-the-entrypoint) - [Transition preparation](#transition-preparation) - [Returning from an exception that never happened](#returning-from-an-exception-that-never-happened) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction Application-grade CPUs have so-called `privilege levels`, which have different purposes: | Typically used for | AArch64 | RISC-V | x86 | | ------------- | ------------- | ------------- | ------------- | | Userspace applications | EL0 | U/VU | Ring 3 | | OS Kernel | EL1 | S/VS | Ring 0 | | Hypervisor | EL2 | HS | Ring -1 | | Low-Level Firmware | EL3 | M | | `EL` in AArch64 stands for `Exception Level`. If you want more information regarding the other architectures, please have a look at the following links: - [x86 privilege rings](https://en.wikipedia.org/wiki/Protection_ring). - [RISC-V privilege modes](https://content.riscv.org/wp-content/uploads/2017/12/Tue0942-riscv-hypervisor-waterman.pdf). At this point, I strongly recommend that you glimpse over `Chapter 3` of the [Programmer’s Guide for ARMv8-A] before you continue. It gives a concise overview about the topic. [Programmer’s Guide for ARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf ## Scope of this tutorial By default, the Raspberry will always start executing in `EL2`. Since we are writing a traditional `Kernel`, we have to transition into the more appropriate `EL1`. ## Checking for EL2 in the entrypoint First of all, we need to ensure that we actually execute in `EL2` before we can call respective code to transition to `EL1`. Therefore, we add a new checkt to the top of `boot.s`, which parks the CPU core should it not be in `EL2`. ``` // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop ``` Afterwards, we continue with preparing the `EL2` -> `EL1` transition by calling `prepare_el2_to_el1_transition()` in `boot.rs`: ```rust #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ``` ## Transition preparation Since `EL2` is more privileged than `EL1`, it has control over various processor features and can allow or disallow `EL1` code to use them. One such example is access to timer and counter registers. We are already using them since [tutorial 07](../07_timestamps/), so of course we want to keep them. Therefore we set the respective flags in the [Counter-timer Hypervisor Control register] and additionally set the virtual offset to zero so that we get the real physical value everytime: [Counter-timer Hypervisor Control register]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/cnthctl_el2.rs.html ```rust // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); ``` Next, we configure the [Hypervisor Configuration Register] such that `EL1` runs in `AArch64` mode, and not in `AArch32`, which would also be possible. [Hypervisor Configuration Register]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/hcr_el2.rs.html ```rust // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); ``` ## Returning from an exception that never happened There is actually only one way to transition from a higher EL to a lower EL, which is by way of executing the [ERET] instruction. [ERET]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/asm.rs.html#92-101 This instruction will copy the contents of the [Saved Program Status Register - EL2] to `Current Program Status Register - EL1` and jump to the instruction address that is stored in the [Exception Link Register - EL2]. This is basically the reverse of what is happening when an exception is taken. You'll learn about that in an upcoming tutorial. [Saved Program Status Register - EL2]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/spsr_el2.rs.html [Exception Link Register - EL2]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/elr_el2.rs.html ```rust // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); ``` As you can see, we are populating `ELR_EL2` with the address of the `kernel_init()` function that we earlier used to call directly from the entrypoint. Finally, we set the stack pointer for `SP_EL1`. You might have noticed that the stack's address was supplied as a function argument. As you might remember, in `_start()` in `boot.s`, we are already setting up the stack for `EL2`. Since there are no plans to ever return to `EL2`, we can just re-use the same stack for `EL1`, so its address is forwarded using function arguments. Lastly, back in `_start_rust()` a call to `ERET` is made: ```rust #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ``` ## Test it In `main.rs`, we print the `current privilege level` and additionally inspect if the mask bits in `SPSR_EL2` made it to `EL1` as well: ```console $ make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 14 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.162546] mingo version 0.9.0 [ 0.162745] Booting on: Raspberry Pi 3 [ 0.163201] Current privilege level: EL1 [ 0.163677] Exception handling state: [ 0.164122] Debug: Masked [ 0.164511] SError: Masked [ 0.164901] IRQ: Masked [ 0.165291] FIQ: Masked [ 0.165681] Architectural timer resolution: 52 ns [ 0.166255] Drivers loaded: [ 0.166592] 1. BCM PL011 UART [ 0.167014] 2. BCM GPIO [ 0.167371] Timer test, spinning for 1 second [ 1.167904] Echoing input now ``` ## Diff to previous ```diff diff -uNr 08_hw_debug_JTAG/Cargo.toml 09_privilege_level/Cargo.toml --- 08_hw_debug_JTAG/Cargo.toml +++ 09_privilege_level/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.8.0" +version = "0.9.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs 09_privilege_level/src/_arch/aarch64/cpu/boot.rs --- 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.rs +++ 09_privilege_level/src/_arch/aarch64/cpu/boot.rs @@ -11,22 +11,73 @@ //! //! crate::cpu::boot::arch_boot +use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; +use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), + CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prepares the transition from EL2 to EL1. +/// +/// # Safety +/// +/// - The `bss` section is not initialized yet. The code must not use or reference it in any way. +/// - The HW state of EL1 must be prepared in a sound way. +#[inline(always)] +unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { + // Enable timer counter registers for EL1. + CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); + + // No offset for reading the counters. + CNTVOFF_EL2.set(0); + + // Set EL1 execution state to AArch64. + HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); + + // Set up a simulated exception return. + // + // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a + // stack pointer. + SPSR_EL2.write( + SPSR_EL2::D::Masked + + SPSR_EL2::A::Masked + + SPSR_EL2::I::Masked + + SPSR_EL2::F::Masked + + SPSR_EL2::M::EL1h, + ); + + // Second, let the link register point to kernel_init(). + ELR_EL2.set(crate::kernel_init as *const () as u64); + + // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there + // are no plans to ever return to EL2, just re-use the same stack. + SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); +} + +//-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. +/// +/// # Safety +/// +/// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] -pub unsafe fn _start_rust() -> ! { - crate::kernel_init() +pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { + prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + asm::eret() } diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s 09_privilege_level/src/_arch/aarch64/cpu/boot.s --- 08_hw_debug_JTAG/src/_arch/aarch64/cpu/boot.s +++ 09_privilege_level/src/_arch/aarch64/cpu/boot.s @@ -27,11 +27,16 @@ // fn _start() //------------------------------------------------------------------------------ _start: + // Only proceed if the core executes in EL2. Park it otherwise. + mrs x0, CurrentEL + cmp x0, {CONST_CURRENTEL_EL2} + b.ne .L_parking_loop + // Only proceed on the boot core. Park it otherwise. - mrs x0, MPIDR_EL1 - and x0, x0, {CONST_CORE_ID_MASK} - ldr x1, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs - cmp x0, x1 + mrs x1, MPIDR_EL1 + and x1, x1, {CONST_CORE_ID_MASK} + ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs + cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. @@ -48,7 +53,7 @@ // Prepare the jump to Rust code. .L_prepare_rust: - // Set the stack pointer. + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 @@ -60,7 +65,7 @@ b.eq .L_parking_loop str w2, [x1] - // Jump to Rust code. + // Jump to Rust code. x0 holds the function argument provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs 09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs --- 08_hw_debug_JTAG/src/_arch/aarch64/exception/asynchronous.rs +++ 09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::asynchronous::arch_asynchronous + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +trait DaifField { + fn daif_field() -> tock_registers::fields::Field; +} + +struct Debug; +struct SError; +struct IRQ; +struct FIQ; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl DaifField for Debug { + fn daif_field() -> tock_registers::fields::Field { + DAIF::D + } +} + +impl DaifField for SError { + fn daif_field() -> tock_registers::fields::Field { + DAIF::A + } +} + +impl DaifField for IRQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::I + } +} + +impl DaifField for FIQ { + fn daif_field() -> tock_registers::fields::Field { + DAIF::F + } +} + +fn is_masked() -> bool +where + T: DaifField, +{ + DAIF.is_set(T::daif_field()) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Print the AArch64 exceptions status. +#[rustfmt::skip] +pub fn print_state() { + use crate::info; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + info!(" Debug: {}", to_mask_str(is_masked::())); + info!(" SError: {}", to_mask_str(is_masked::())); + info!(" IRQ: {}", to_mask_str(is_masked::())); + info!(" FIQ: {}", to_mask_str(is_masked::())); +} diff -uNr 08_hw_debug_JTAG/src/_arch/aarch64/exception.rs 09_privilege_level/src/_arch/aarch64/exception.rs --- 08_hw_debug_JTAG/src/_arch/aarch64/exception.rs +++ 09_privilege_level/src/_arch/aarch64/exception.rs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural synchronous and asynchronous exception handling. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::exception::arch_exception + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use crate::exception::PrivilegeLevel; + +/// The processing element's current privilege level. +pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { + let el = CurrentEL.read_as_enum(CurrentEL::EL); + match el { + Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), + Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), + Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), + _ => (PrivilegeLevel::Unknown, "Unknown"), + } +} diff -uNr 08_hw_debug_JTAG/src/exception/asynchronous.rs 09_privilege_level/src/exception/asynchronous.rs --- 08_hw_debug_JTAG/src/exception/asynchronous.rs +++ 09_privilege_level/src/exception/asynchronous.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/exception/asynchronous.rs"] +mod arch_asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_asynchronous::print_state; diff -uNr 08_hw_debug_JTAG/src/exception.rs 09_privilege_level/src/exception.rs --- 08_hw_debug_JTAG/src/exception.rs +++ 09_privilege_level/src/exception.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Synchronous and asynchronous exception handling. + +#[cfg(target_arch = "aarch64")] +#[path = "_arch/aarch64/exception.rs"] +mod arch_exception; + +pub mod asynchronous; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_exception::current_privilege_level; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Kernel privilege levels. +#[allow(missing_docs)] +#[derive(Eq, PartialEq)] +pub enum PrivilegeLevel { + User, + Kernel, + Hypervisor, + Unknown, +} diff -uNr 08_hw_debug_JTAG/src/main.rs 09_privilege_level/src/main.rs --- 08_hw_debug_JTAG/src/main.rs +++ 09_privilege_level/src/main.rs @@ -121,6 +121,7 @@ mod console; mod cpu; mod driver; +mod exception; mod panic_wait; mod print; mod synchronization; @@ -148,6 +149,7 @@ /// The main function running after the early init. fn kernel_main() -> ! { + use console::console; use core::time::Duration; info!( @@ -157,6 +159,12 @@ ); info!("Booting on: {}", bsp::board_name()); + let (_, privilege_level) = exception::current_privilege_level(); + info!("Current privilege level: {}", privilege_level); + + info!("Exception handling state:"); + exception::asynchronous::print_state(); + info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() @@ -165,11 +173,15 @@ info!("Drivers loaded:"); driver::driver_manager().enumerate(); - // Test a failing timer case. - time::time_manager().spin_for(Duration::from_nanos(1)); + info!("Timer test, spinning for 1 second"); + time::time_manager().spin_for(Duration::from_secs(1)); + + info!("Echoing input now"); + // Discard any spurious received characters before going into echo mode. + console().clear_rx(); loop { - info!("Spinning for 1 second"); - time::time_manager().spin_for(Duration::from_secs(1)); + let c = console().read_char(); + console().write_char(c); } } diff -uNr 08_hw_debug_JTAG/tests/boot_test_string.rb 09_privilege_level/tests/boot_test_string.rb --- 08_hw_debug_JTAG/tests/boot_test_string.rb +++ 09_privilege_level/tests/boot_test_string.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -EXPECTED_PRINT = 'Spinning for 1 second' +EXPECTED_PRINT = 'Echoing input now' ``` ================================================ FILE: 09_privilege_level/build.rs ================================================ 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())); } ================================================ FILE: 09_privilege_level/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prepares the transition from EL2 to EL1. /// /// # Safety /// /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. /// /// # Safety /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ================================================ FILE: 09_privilege_level/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. x0 holds the function argument provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 09_privilege_level/src/_arch/aarch64/cpu.rs ================================================ // 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() } } ================================================ FILE: 09_privilege_level/src/_arch/aarch64/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::asynchronous::arch_asynchronous use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- trait DaifField { fn daif_field() -> tock_registers::fields::Field; } struct Debug; struct SError; struct IRQ; struct FIQ; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl DaifField for Debug { fn daif_field() -> tock_registers::fields::Field { DAIF::D } } impl DaifField for SError { fn daif_field() -> tock_registers::fields::Field { DAIF::A } } impl DaifField for IRQ { fn daif_field() -> tock_registers::fields::Field { DAIF::I } } impl DaifField for FIQ { fn daif_field() -> tock_registers::fields::Field { DAIF::F } } fn is_masked() -> bool where T: DaifField, { DAIF.is_set(T::daif_field()) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Print the AArch64 exceptions status. #[rustfmt::skip] pub fn print_state() { use crate::info; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; info!(" Debug: {}", to_mask_str(is_masked::())); info!(" SError: {}", to_mask_str(is_masked::())); info!(" IRQ: {}", to_mask_str(is_masked::())); info!(" FIQ: {}", to_mask_str(is_masked::())); } ================================================ FILE: 09_privilege_level/src/_arch/aarch64/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::arch_exception use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use crate::exception::PrivilegeLevel; /// The processing element's current privilege level. pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { let el = CurrentEL.read_as_enum(CurrentEL::EL); match el { Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), _ => (PrivilegeLevel::Unknown, "Unknown"), } } ================================================ FILE: 09_privilege_level/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 09_privilege_level/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 09_privilege_level/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 09_privilege_level/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 09_privilege_level/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 09_privilege_level/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 09_privilege_level/src/bsp/raspberrypi/driver.rs ================================================ // 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(()) } ================================================ FILE: 09_privilege_level/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 09_privilege_level/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } } ================================================ FILE: 09_privilege_level/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 09_privilege_level/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 09_privilege_level/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 09_privilege_level/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 09_privilege_level/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 09_privilege_level/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; ================================================ FILE: 09_privilege_level/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 09_privilege_level/src/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/exception/asynchronous.rs"] mod arch_asynchronous; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_asynchronous::print_state; ================================================ FILE: 09_privilege_level/src/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/exception.rs"] mod arch_exception; pub mod asynchronous; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_exception::current_privilege_level; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Kernel privilege levels. #[allow(missing_docs)] #[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, Hypervisor, Unknown, } ================================================ FILE: 09_privilege_level/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] #![feature(const_option)] #![feature(format_args_nl)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod driver; mod exception; mod panic_wait; mod print; mod synchronization; mod time; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { use console::console; use core::time::Duration; info!( "{} version {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION") ); info!("Booting on: {}", bsp::board_name()); let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); info!("Exception handling state:"); exception::asynchronous::print_state(); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); info!("Echoing input now"); // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { let c = console().read_char(); console().write_char(c); } } ================================================ FILE: 09_privilege_level/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", timestamp.as_secs(), timestamp.subsec_micros(), location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 09_privilege_level/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 09_privilege_level/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 09_privilege_level/src/time.rs ================================================ // 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) } } ================================================ FILE: 09_privilege_level/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 10_virtual_mem_part1_identity_mapping/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/Cargo.toml ================================================ [package] name = "mingo" version = "0.10.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 10_virtual_mem_part1_identity_mapping/README.CN.md ================================================ # 教程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),这是最新的。 ================================================ FILE: 10_virtual_mem_part1_identity_mapping/README.md ================================================ # Tutorial 10 - Virtual Memory Part 1: Identity Map All The Things! ## tl;dr - The `MMU` is turned on. - A simple scheme is used: Static `64 KiB` translation tables. - For educational purposes, we write to a remapped `UART`, and `identity map` everything else. ## Table of Contents - [Introduction](#introduction) - [MMU and paging theory](#mmu-and-paging-theory) - [Approach](#approach) * [Generic Kernel code: `memory/mmu.rs`](#generic-kernel-code-memorymmurs) * [BSP: `bsp/raspberrypi/memory/mmu.rs`](#bsp-bspraspberrypimemorymmurs) * [AArch64: `_arch/aarch64/memory/*`](#aarch64-_archaarch64memory) * [`kernel.ld`](#kernelld) - [Address translation examples](#address-translation-examples) * [Address translation using a 64 KiB page descriptor](#address-translation-using-a-64-kib-page-descriptor) - [Zero-cost abstraction](#zero-cost-abstraction) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction Virtual memory is an immensely complex, but important and powerful topic. In this tutorial, we start slow and easy by switching on the `MMU`, using static translation tables and `identity-map` everything at once (except for the `UART`, which we also remap a second time for educational purposes; This will be gone again in the next tutorial). ## MMU and paging theory At this point, we will not re-invent the wheel and go into detailed descriptions of how paging in modern application-grade processors works. The internet is full of great resources regarding this topic, and we encourage you to read some of it to get a high-level understanding of the topic. To follow the rest of this `AArch64` specific tutorial, I strongly recommend that you stop right here and first read `Chapter 12` of the [ARM Cortex-A Series Programmer's Guide for ARMv8-A] before you continue. This will set you up with all the `AArch64`-specific knowledge needed to follow along. Back from reading `Chapter 12` already? Good job :+1:! [ARM Cortex-A Series Programmer's Guide for ARMv8-A]: http://infocenter.arm.com/help/topic/com.arm.doc.den0024a/DEN0024A_v8_architecture_PG.pdf ## Approach 1. The generic `kernel` part: `src/memory/mmu.rs` and its submodules provide architecture-agnostic descriptor types for composing a high-level data structure that describes the kernel's virtual memory layout: `memory::mmu::KernelVirtualLayout`. 2. The `BSP` part: `src/bsp/raspberrypi/memory/mmu.rs` contains a static instance of `KernelVirtualLayout` and makes it accessible through the function `bsp::memory::mmu::virt_mem_layout()`. 3. The `aarch64` part: `src/_arch/aarch64/memory/mmu.rs` and its submodules contain the actual `MMU` driver. It picks up the `BSP`'s high-level `KernelVirtualLayout` and maps it using a `64 KiB` granule. ### Generic Kernel code: `memory/mmu.rs` The descriptor types provided in this file are building blocks which help to describe attributes of different memory regions. For example, `R/W`, `no-execute`, `cached/uncached`, and so on. The descriptors are agnostic of the hardware `MMU`'s actual descriptors. Different `BSP`s can use these types to produce a high-level description of the kernel's virtual memory layout. The actual `MMU` driver for the real HW will consume these types as an input. This way, we achieve a clean abstraction between `BSP` and `_arch` code, which allows exchanging one without needing to adapt the other. ### BSP: `bsp/raspberrypi/memory/mmu.rs` This file contains an instance of `KernelVirtualLayout`, which stores the descriptors mentioned previously. The `BSP` is the correct place to do this, because it has knowledge of the target board's memory map. The policy is to only describe regions that are **not** ordinary, normal cacheable DRAM. However, nothing prevents you from defining those too if you wish to. Here is an example for the device MMIO region: ```rust TranslationDescriptor { name: "Device MMIO", virtual_range: mmio_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, }, ``` `KernelVirtualLayout` itself implements the following method: ```rust pub fn virt_addr_properties( &self, virt_addr: usize, ) -> Result<(usize, AttributeFields), &'static str> ``` It will be used by `_arch/aarch64`'s `MMU` code to request attributes for a virtual address and the translation, which delivers the physical output address (the `usize` in the return-tuple). The function scans for a descriptor that contains the queried address, and returns the respective findings for the first entry that is a hit. If no entry is found, it returns default attributes for normal cacheable DRAM and the input address, hence telling the `MMU` code that the requested address should be `identity mapped`. Due to this default behavior, it is not needed to define normal cacheable DRAM regions. ### AArch64: `_arch/aarch64/memory/*` These modules contain the `AArch64` `MMU` driver. The granule is hardcoded here (`64 KiB` page descriptors). In `translation_table.rs`, there is a definition of the actual translation table struct which is generic over the number of `LVL2` tables. The latter depends on the size of the target board's memory. Naturally, the `BSP` knows these details about the target board, and provides the size through the constant `bsp::memory::mmu::KernelAddrSpace::SIZE`. This information is used by `translation_table.rs` to calculate the number of needed `LVL2` tables. Since one `LVL2` table in a `64 KiB` configuration covers `512 MiB`, all that needs to be done is to divide `KernelAddrSpace::SIZE` by `512 MiB` (there are several compile-time checks in place that ensure that `KernelAddrSpace::SIZE` is a multiple of `512 MiB`). The final table type is exported as `KernelTranslationTable`. Below is the respective excerpt from `translation_table.rs`: ```rust /// A table descriptor for 64 KiB aperture. /// /// The output points to the next table. #[derive(Copy, Clone)] #[repr(C)] struct TableDescriptor { value: u64, } /// A page descriptor with 64 KiB aperture. /// /// The output points to physical memory. #[derive(Copy, Clone)] #[repr(C)] struct PageDescriptor { value: u64, } const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB /// aligned, hence the "reverse" order of appearance. #[repr(C)] #[repr(align(65536))] pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], } /// A translation table type for the kernel space. pub type KernelTranslationTable = FixedSizeTranslationTable; ``` In `mmu.rs`, `KernelTranslationTable` is then used to create the final instance of the kernel's tables: ```rust //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); ``` They are populated during `MMU::init()` by calling `KERNEL_TABLES.populate_tt_entries()`, which utilizes `bsp::memory::mmu::virt_mem_layout().virt_addr_properties()` and a bunch of utility functions that convert the kernel generic descriptors to the actual `64 bit` integer entries needed by the `AArch64 MMU` hardware for the translation table arrays. One notable thing is that each page descriptor has an entry (`AttrIndex`) that indexes into the [MAIR_EL1] register, which holds information about the cacheability of the respective page. We currently define normal cacheable memory and device memory (which is not cached). [MAIR_EL1]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500d/CIHDHJBB.html ```rust impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } ``` Afterwards, the [Translation Table Base Register 0 - EL1] is set up with the base address of the `lvl2` tables and the [Translation Control Register - EL1] is configured: ```rust // Set the "Translation Table Base Register". TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); self.configure_translation_control(); ``` Finally, the `MMU` is turned on through the [System Control Register - EL1]. The last step also enables caching for data and instructions. [Translation Table Base Register 0 - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/ttbr0_el1.rs.html [Translation Control Register - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/tcr_el1.rs.html [System Control Register - EL1]: https://docs.rs/aarch64-cpu/9.0.0/src/aarch64_cpu/registers/sctlr_el1.rs.html ### `kernel.ld` We need to align the `code` segment to `64 KiB` so that it doesn't overlap with the next section that needs read/write attributes instead of read/execute attributes: ```ld.s . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; ``` This blows up the binary in size, but is a small price to pay considering that it reduces the amount of static paging entries significantly, when compared to the classical `4 KiB` granule. ## Address translation examples For educational purposes, a layout is defined which allows to access the `UART` via two different virtual addresses: - Since we identity map the whole `Device MMIO` region, it is accessible by asserting its physical base address (`0x3F20_1000` or `0xFA20_1000` depending on which RPi you use) after the `MMU` is turned on. - Additionally, it is also mapped into the last `64 KiB` slot in the first `512 MiB`, making it accessible through base address `0x1FFF_1000`. The following block diagram visualizes the underlying translation for the second mapping. ### Address translation using a 64 KiB page descriptor Page Tables 64KiB ## Zero-cost abstraction The MMU init code is again a good example to see the great potential of Rust's zero-cost abstractions[[1]][[2]] for embedded programming. Let's take a look again at the piece of code for setting up the `MAIR_EL1` register using the [aarch64-cpu] crate: [1]: https://blog.rust-lang.org/2015/05/11/traits.html [2]: https://ruudvanasseldonk.com/2016/11/30/zero-cost-abstractions [aarch64-cpu]: https://crates.io/crates/aarch64-cpu ```rust /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } ``` This piece of code is super expressive, and it makes use of `traits`, different `types` and `constants` to provide type-safe register manipulation. In the end, this code sets the first four bytes of the register to certain values according to the data sheet. Looking at the generated code, we can see that despite all the type-safety and abstractions, it boils down to two assembly instructions: ```text 800a8: 529fe089 mov w9, #0xff04 // #65284 800ac: d518a209 msr mair_el1, x9 ``` ## Test it Turning on virtual memory is now the first thing we do during kernel init: ```rust unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { panic!("MMU: {}", string); } ``` Later in the boot process, prints about the mappings can be observed: ```console $ make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 64 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.811167] mingo version 0.10.0 [ 0.811374] Booting on: Raspberry Pi 3 [ 0.811829] MMU online. Special regions: [ 0.812306] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data [ 0.813324] 0x1fff0000 - 0x1fffffff | 64 KiB | Dev RW PXN | Remapped Device MMIO [ 0.814310] 0x3f000000 - 0x4000ffff | 17 MiB | Dev RW PXN | Device MMIO [ 0.815198] Current privilege level: EL1 [ 0.815675] Exception handling state: [ 0.816119] Debug: Masked [ 0.816509] SError: Masked [ 0.816899] IRQ: Masked [ 0.817289] FIQ: Masked [ 0.817679] Architectural timer resolution: 52 ns [ 0.818253] Drivers loaded: [ 0.818589] 1. BCM PL011 UART [ 0.819011] 2. BCM GPIO [ 0.819369] Timer test, spinning for 1 second [ !!! ] Writing through the remapped UART at 0x1FFF_1000 [ 1.820409] Echoing input now ``` ## Diff to previous ```diff diff -uNr 09_privilege_level/Cargo.toml 10_virtual_mem_part1_identity_mapping/Cargo.toml --- 09_privilege_level/Cargo.toml +++ 10_virtual_mem_part1_identity_mapping/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.9.0" +version = "0.10.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu/translation_table.rs 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs --- 09_privilege_level/src/_arch/aarch64/memory/mmu/translation_table.rs +++ 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Architectural translation table. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::translation_table::arch_translation_table + +use crate::{ + bsp, memory, + memory::mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, + }, +}; +use core::convert; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, + registers::InMemoryRegister, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. +register_bitfields! {u64, + STAGE1_TABLE_DESCRIPTOR [ + /// Physical address of the next descriptor. + NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + TYPE OFFSET(1) NUMBITS(1) [ + Block = 0, + Table = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +// A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. +register_bitfields! {u64, + STAGE1_PAGE_DESCRIPTOR [ + /// Unprivileged execute-never. + UXN OFFSET(54) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Privileged execute-never. + PXN OFFSET(53) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). + OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] + + /// Access flag. + AF OFFSET(10) NUMBITS(1) [ + False = 0, + True = 1 + ], + + /// Shareability field. + SH OFFSET(8) NUMBITS(2) [ + OuterShareable = 0b10, + InnerShareable = 0b11 + ], + + /// Access Permissions. + AP OFFSET(6) NUMBITS(2) [ + RW_EL1 = 0b00, + RW_EL1_EL0 = 0b01, + RO_EL1 = 0b10, + RO_EL1_EL0 = 0b11 + ], + + /// Memory attributes index into the MAIR_EL1 register. + AttrIndx OFFSET(2) NUMBITS(3) [], + + TYPE OFFSET(1) NUMBITS(1) [ + Reserved_Invalid = 0, + Page = 1 + ], + + VALID OFFSET(0) NUMBITS(1) [ + False = 0, + True = 1 + ] + ] +} + +/// A table descriptor for 64 KiB aperture. +/// +/// The output points to the next table. +#[derive(Copy, Clone)] +#[repr(C)] +struct TableDescriptor { + value: u64, +} + +/// A page descriptor with 64 KiB aperture. +/// +/// The output points to physical memory. +#[derive(Copy, Clone)] +#[repr(C)] +struct PageDescriptor { + value: u64, +} + +trait StartAddr { + fn phys_start_addr_u64(&self) -> u64; + fn phys_start_addr_usize(&self) -> usize; +} + +const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB +/// aligned, so the lvl3 is put first. +#[repr(C)] +#[repr(align(65536))] +pub struct FixedSizeTranslationTable { + /// Page descriptors, covering 64 KiB windows per entry. + lvl3: [[PageDescriptor; 8192]; NUM_TABLES], + + /// Table descriptors, covering 512 MiB windows. + lvl2: [TableDescriptor; NUM_TABLES], +} + +/// A translation table type for the kernel space. +pub type KernelTranslationTable = FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +// The binary is still identity mapped, so we don't need to convert here. +impl StartAddr for [T; N] { + fn phys_start_addr_u64(&self) -> u64 { + self as *const T as u64 + } + + fn phys_start_addr_usize(&self) -> usize { + self as *const _ as usize + } +} + +impl TableDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance pointing to the supplied address. + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; + val.write( + STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + + STAGE1_TABLE_DESCRIPTOR::VALID::True, + ); + + TableDescriptor { value: val.get() } + } +} + +/// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. +impl convert::From + for tock_registers::fields::FieldValue +{ + fn from(attribute_fields: AttributeFields) -> Self { + // Memory attributes. + let mut desc = match attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => { + STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) + } + MemAttributes::Device => { + STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) + } + }; + + // Access Permissions. + desc += match attribute_fields.acc_perms { + AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, + AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, + }; + + // The execute-never attribute is mapped to PXN in AArch64. + desc += if attribute_fields.execute_never { + STAGE1_PAGE_DESCRIPTOR::PXN::True + } else { + STAGE1_PAGE_DESCRIPTOR::PXN::False + }; + + // Always set unprivileged exectue-never as long as userspace is not implemented yet. + desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; + + desc + } +} + +impl PageDescriptor { + /// Create an instance. + /// + /// Descriptor is invalid by default. + pub const fn new_zeroed() -> Self { + Self { value: 0 } + } + + /// Create an instance. + pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { + let val = InMemoryRegister::::new(0); + + let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; + val.write( + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + + STAGE1_PAGE_DESCRIPTOR::AF::True + + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + + STAGE1_PAGE_DESCRIPTOR::VALID::True + + (*attribute_fields).into(), + ); + + Self { value: val.get() } + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl FixedSizeTranslationTable { + /// Create an instance. + pub const fn new() -> Self { + // Can't have a zero-sized address space. + assert!(NUM_TABLES > 0); + + Self { + lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], + lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + } + } + + /// Iterates over all static translation table entries and fills them at once. + /// + /// # Safety + /// + /// - Modifies a `static mut`. Ensure it only happens from here. + pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { + for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { + *l2_entry = + TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); + + for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { + let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); + + let (phys_output_addr, attribute_fields) = + bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; + + *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); + } + } + + Ok(()) + } + + /// The translation table's base address to be used for programming the MMU. + pub fn phys_base_address(&self) -> u64 { + self.lvl2.phys_start_addr_u64() + } +} diff -uNr 09_privilege_level/src/_arch/aarch64/memory/mmu.rs 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs --- 09_privilege_level/src/_arch/aarch64/memory/mmu.rs +++ 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management Unit Driver. +//! +//! Only 64 KiB granule is supported. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::memory::mmu::arch_mmu + +use crate::{ + bsp, memory, + memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, +}; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::intrinsics::unlikely; +use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Memory Management Unit type. +struct MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; +pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; + +/// Constants for indexing the MAIR_EL1. +#[allow(dead_code)] +pub mod mair { + pub const DEVICE: u64 = 0; + pub const NORMAL: u64 = 1; +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +/// The kernel translation tables. +/// +/// # Safety +/// +/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". +static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); + +static MMU: MemoryManagementUnit = MemoryManagementUnit; + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl memory::mmu::AddressSpace { + /// Checks for architectural restrictions. + pub const fn arch_address_space_size_sanity_checks() { + // Size must be at least one full 512 MiB table. + assert!((AS_SIZE modulo Granule512MiB::SIZE) == 0); + + // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 + // version. + assert!(AS_SIZE <= (1 << 48)); + } +} + +impl MemoryManagementUnit { + /// Setup function for the MAIR_EL1 register. + fn set_up_mair(&self) { + // Define the memory types being mapped. + MAIR_EL1.write( + // Attribute 1 - Cacheable normal DRAM. + MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + + + // Attribute 0 - Device. + MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, + ); + } + + /// Configure various settings of stage 1 of the EL1 translation regime. + fn configure_translation_control(&self) { + let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; + + TCR_EL1.write( + TCR_EL1::TBI0::Used + + TCR_EL1::IPS::Bits_40 + + TCR_EL1::TG0::KiB_64 + + TCR_EL1::SH0::Inner + + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD0::EnableTTBR0Walks + + TCR_EL1::A1::TTBR0 + + TCR_EL1::T0SZ.val(t0sz) + + TCR_EL1::EPD1::DisableTTBR1Walks, + ); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the MMU instance. +pub fn mmu() -> &'static impl memory::mmu::interface::MMU { + &MMU +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use memory::mmu::MMUEnableError; + +impl memory::mmu::interface::MMU for MemoryManagementUnit { + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { + if unlikely(self.is_enabled()) { + return Err(MMUEnableError::AlreadyEnabled); + } + + // Fail early if translation granule is not supported. + if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { + return Err(MMUEnableError::Other( + "Translation granule not supported in HW", + )); + } + + // Prepare the memory attribute indirection register. + self.set_up_mair(); + + // Populate translation tables. + KERNEL_TABLES + .populate_tt_entries() + .map_err(MMUEnableError::Other)?; + + // Set the "Translation Table Base Register". + TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + + self.configure_translation_control(); + + // Switch the MMU on. + // + // First, force all previous changes to be seen before the MMU is enabled. + barrier::isb(barrier::SY); + + // Enable the MMU and turn on data and instruction caching. + SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); + + // Force MMU init to complete before next instruction. + barrier::isb(barrier::SY); + + Ok(()) + } + + #[inline(always)] + fn is_enabled(&self) -> bool { + SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) + } +} diff -uNr 09_privilege_level/src/bsp/raspberrypi/kernel.ld 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld --- 09_privilege_level/src/bsp/raspberrypi/kernel.ld +++ 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld @@ -3,6 +3,9 @@ * Copyright (c) 2018-2023 Andre Richter */ +PAGE_SIZE = 64K; +PAGE_MASK = PAGE_SIZE - 1; + __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ @@ -42,9 +45,12 @@ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ + __code_start = .; .text : { KEEP(*(.text._start)) @@ -55,6 +61,9 @@ .rodata : ALIGN(8) { *(.rodata*) } :segment_code + . = ALIGN(PAGE_SIZE); + __code_end_exclusive = .; + /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ diff -uNr 09_privilege_level/src/bsp/raspberrypi/memory/mmu.rs 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs --- 09_privilege_level/src/bsp/raspberrypi/memory/mmu.rs +++ 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! BSP Memory Management Unit. + +use super::map as memory_map; +use crate::memory::mmu::*; +use core::ops::RangeInclusive; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// The kernel's address space defined by this BSP. +pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; + +const NUM_MEM_RANGES: usize = 3; + +/// The virtual memory layout. +/// +/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. +/// It is agnostic of the paging granularity that the architecture's MMU will use. +pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( + memory_map::END_INCLUSIVE, + [ + TranslationDescriptor { + name: "Kernel code and RO data", + virtual_range: code_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + }, + TranslationDescriptor { + name: "Remapped Device MMIO", + virtual_range: remapped_mmio_range_inclusive, + physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + }, + TranslationDescriptor { + name: "Device MMIO", + virtual_range: mmio_range_inclusive, + physical_range_translation: Translation::Identity, + attribute_fields: AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + }, + ], +); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +fn code_range_inclusive() -> RangeInclusive { + // Notice the subtraction to turn the exclusive end into an inclusive end. + #[allow(clippy::range_minus_one)] + RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) +} + +fn remapped_mmio_range_inclusive() -> RangeInclusive { + // The last 64 KiB slot in the first 512 MiB + RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) +} + +fn mmio_range_inclusive() -> RangeInclusive { + RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the virtual memory layout. +pub fn virt_mem_layout() -> &'static KernelVirtualLayout { + &LAYOUT +} diff -uNr 09_privilege_level/src/bsp/raspberrypi/memory.rs 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs --- 09_privilege_level/src/bsp/raspberrypi/memory.rs +++ 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs @@ -3,6 +3,45 @@ // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. +//! +//! The physical memory layout. +//! +//! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used +//! as the boot core's stack. +//! +//! +---------------------------------------+ +//! | | 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | +//! | | +pub mod mmu; + +use core::cell::UnsafeCell; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +// Symbols from the linker script. +extern "Rust" { + static __code_start: UnsafeCell<()>; + static __code_end_exclusive: UnsafeCell<()>; +} //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -11,6 +50,20 @@ /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { + /// The inclusive end address of the memory map. + /// + /// End address + 1 must be power of two. + /// + /// # Note + /// + /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for + /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. + /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. + /// + /// However, making this trade-off has the downside of making it possible for the CPU to assert a + /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on + /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. + pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; @@ -23,6 +76,7 @@ pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0x4000_FFFF; } /// Physical devices. @@ -33,5 +87,29 @@ pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0xFF84_FFFF; } } + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Start page address of the code segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_start() -> usize { + unsafe { __code_start.get() as usize } +} + +/// Exclusive end page address of the code segment. +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn code_end_exclusive() -> usize { + unsafe { __code_end_exclusive.get() as usize } +} diff -uNr 09_privilege_level/src/bsp.rs 10_virtual_mem_part1_identity_mapping/src/bsp.rs --- 09_privilege_level/src/bsp.rs +++ 10_virtual_mem_part1_identity_mapping/src/bsp.rs @@ -4,7 +4,7 @@ //! Conditional reexporting of Board Support Packages. -mod device_driver; +pub mod device_driver; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; diff -uNr 09_privilege_level/src/common.rs 10_virtual_mem_part1_identity_mapping/src/common.rs --- 09_privilege_level/src/common.rs +++ 10_virtual_mem_part1_identity_mapping/src/common.rs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! General purpose code. + +/// Convert a size into human readable format. +pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { + const KIB: usize = 1024; + const MIB: usize = 1024 * 1024; + const GIB: usize = 1024 * 1024 * 1024; + + if (size / GIB) > 0 { + (size.div_ceil(GIB), "GiB") + } else if (size / MIB) > 0 { + (size.div_ceil(MIB), "MiB") + } else if (size / KIB) > 0 { + (size.div_ceil(KIB), "KiB") + } else { + (size, "Byte") + } +} diff -uNr 09_privilege_level/src/main.rs 10_virtual_mem_part1_identity_mapping/src/main.rs --- 09_privilege_level/src/main.rs +++ 10_virtual_mem_part1_identity_mapping/src/main.rs @@ -107,9 +107,12 @@ //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] +#![allow(incomplete_features)] #![feature(asm_const)] #![feature(const_option)] +#![feature(core_intrinsics)] #![feature(format_args_nl)] +#![feature(int_roundings)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] @@ -118,10 +121,12 @@ #![no_std] mod bsp; +mod common; mod console; mod cpu; mod driver; mod exception; +mod memory; mod panic_wait; mod print; mod synchronization; @@ -132,8 +137,17 @@ /// # Safety /// /// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order. +/// - The init calls in this function must appear in the correct order: +/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, +/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ +/// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. unsafe fn kernel_init() -> ! { + use memory::mmu::interface::MMU; + + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { + panic!("MMU: {}", string); + } + // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); @@ -149,7 +163,7 @@ /// The main function running after the early init. fn kernel_main() -> ! { - use console::console; + use console::{console, interface::Write}; use core::time::Duration; info!( @@ -159,6 +173,9 @@ ); info!("Booting on: {}", bsp::board_name()); + info!("MMU online. Special regions:"); + bsp::memory::mmu::virt_mem_layout().print_layout(); + let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); @@ -176,6 +193,13 @@ info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); + let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; + writeln!( + remapped_uart, + "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" + ) + .unwrap(); + info!("Echoing input now"); // Discard any spurious received characters before going into echo mode. diff -uNr 09_privilege_level/src/memory/mmu/translation_table.rs 10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs --- 09_privilege_level/src/memory/mmu/translation_table.rs +++ 10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Translation table. + +#[cfg(target_arch = "aarch64")] +#[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] +mod arch_translation_table; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_translation_table::KernelTranslationTable; diff -uNr 09_privilege_level/src/memory/mmu.rs 10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs --- 09_privilege_level/src/memory/mmu.rs +++ 10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit. +//! +//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file +//! provides types for composing an architecture-agnostic description of the kernel's virtual memory +//! layout. +//! +//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` +//! function. +//! +//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and +//! install respective translation tables. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/memory/mmu.rs"] +mod arch_mmu; + +mod translation_table; + +use crate::common; +use core::{fmt, ops::RangeInclusive}; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_mmu::mmu; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// MMU enable errors variants. +#[allow(missing_docs)] +#[derive(Debug)] +pub enum MMUEnableError { + AlreadyEnabled, + Other(&'static str), +} + +/// Memory Management interfaces. +pub mod interface { + use super::*; + + /// MMU functions. + pub trait MMU { + /// Called by the kernel during early init. Supposed to take the translation tables from the + /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. + /// + /// # Safety + /// + /// - Changes the HW's global state. + unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; + + /// Returns true if the MMU is enabled, false otherwise. + fn is_enabled(&self) -> bool; + } +} + +/// Describes the characteristics of a translation granule. +pub struct TranslationGranule; + +/// Describes properties of an address space. +pub struct AddressSpace; + +/// Architecture agnostic translation types. +#[allow(missing_docs)] +#[allow(dead_code)] +#[derive(Copy, Clone)] +pub enum Translation { + Identity, + Offset(usize), +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// Architecture agnostic descriptor for a memory range. +#[allow(missing_docs)] +pub struct TranslationDescriptor { + pub name: &'static str, + pub virtual_range: fn() -> RangeInclusive, + pub physical_range_translation: Translation, + pub attribute_fields: AttributeFields, +} + +/// Type for expressing the kernel's virtual memory layout. +pub struct KernelVirtualLayout { + /// The last (inclusive) address of the address space. + max_virt_addr_inclusive: usize, + + /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. + inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for MMUEnableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), + MMUEnableError::Other(x) => write!(f, "{}", x), + } + } +} + +impl TranslationGranule { + /// The granule's size. + pub const SIZE: usize = Self::size_checked(); + + /// The granule's shift, aka log2(size). + pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(GRANULE_SIZE.is_power_of_two()); + + GRANULE_SIZE + } +} + +impl AddressSpace { + /// The address space size. + pub const SIZE: usize = Self::size_checked(); + + /// The address space shift, aka log2(size). + pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; + + const fn size_checked() -> usize { + assert!(AS_SIZE.is_power_of_two()); + + // Check for architectural restrictions as well. + Self::arch_address_space_size_sanity_checks(); + + AS_SIZE + } +} + +impl Default for AttributeFields { + fn default() -> AttributeFields { + AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + } + } +} + +/// Human-readable output of a TranslationDescriptor. +impl fmt::Display for TranslationDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Call the function to which self.range points, and dereference the result, which causes + // Rust to copy the value. + let start = *(self.virtual_range)().start(); + let end = *(self.virtual_range)().end(); + let size = end - start + 1; + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match self.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match self.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if self.attribute_fields.execute_never { + "PXN" + } else { + "PX" + }; + + write!( + f, + " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", + start, end, size, unit, attr, acc_p, xn, self.name + ) + } +} + +impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { + /// Create a new instance. + pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { + Self { + max_virt_addr_inclusive: max, + inner: layout, + } + } + + /// For a virtual address, find and return the physical output address and corresponding + /// attributes. + /// + /// If the address is not found in `inner`, return an identity mapped default with normal + /// cacheable DRAM attributes. + pub fn virt_addr_properties( + &self, + virt_addr: usize, + ) -> Result<(usize, AttributeFields), &'static str> { + if virt_addr > self.max_virt_addr_inclusive { + return Err("Address out of range"); + } + + for i in self.inner.iter() { + if (i.virtual_range)().contains(&virt_addr) { + let output_addr = match i.physical_range_translation { + Translation::Identity => virt_addr, + Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), + }; + + return Ok((output_addr, i.attribute_fields)); + } + } + + Ok((virt_addr, AttributeFields::default())) + } + + /// Print the memory layout. + pub fn print_layout(&self) { + use crate::info; + + for i in self.inner.iter() { + info!("{}", i); + } + } +} diff -uNr 09_privilege_level/src/memory.rs 10_virtual_mem_part1_identity_mapping/src/memory.rs --- 09_privilege_level/src/memory.rs +++ 10_virtual_mem_part1_identity_mapping/src/memory.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Memory Management. + +pub mod mmu; ``` ================================================ FILE: 10_virtual_mem_part1_identity_mapping/build.rs ================================================ 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())); } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prepares the transition from EL2 to EL1. /// /// # Safety /// /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. /// /// # Safety /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. x0 holds the function argument provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/cpu.rs ================================================ // 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() } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::asynchronous::arch_asynchronous use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- trait DaifField { fn daif_field() -> tock_registers::fields::Field; } struct Debug; struct SError; struct IRQ; struct FIQ; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl DaifField for Debug { fn daif_field() -> tock_registers::fields::Field { DAIF::D } } impl DaifField for SError { fn daif_field() -> tock_registers::fields::Field { DAIF::A } } impl DaifField for IRQ { fn daif_field() -> tock_registers::fields::Field { DAIF::I } } impl DaifField for FIQ { fn daif_field() -> tock_registers::fields::Field { DAIF::F } } fn is_masked() -> bool where T: DaifField, { DAIF.is_set(T::daif_field()) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Print the AArch64 exceptions status. #[rustfmt::skip] pub fn print_state() { use crate::info; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; info!(" Debug: {}", to_mask_str(is_masked::())); info!(" SError: {}", to_mask_str(is_masked::())); info!(" IRQ: {}", to_mask_str(is_masked::())); info!(" FIQ: {}", to_mask_str(is_masked::())); } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::arch_exception use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use crate::exception::PrivilegeLevel; /// The processing element's current privilege level. pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { let el = CurrentEL.read_as_enum(CurrentEL::EL); match el { Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), _ => (PrivilegeLevel::Unknown, "Unknown"), } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::translation_table::arch_translation_table use crate::{ bsp, memory, memory::mmu::{ arch_mmu::{Granule512MiB, Granule64KiB}, AccessPermissions, AttributeFields, MemAttributes, }, }; use core::convert; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, registers::InMemoryRegister, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. register_bitfields! {u64, STAGE1_TABLE_DESCRIPTOR [ /// Physical address of the next descriptor. NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] TYPE OFFSET(1) NUMBITS(1) [ Block = 0, Table = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } // A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. register_bitfields! {u64, STAGE1_PAGE_DESCRIPTOR [ /// Unprivileged execute-never. UXN OFFSET(54) NUMBITS(1) [ False = 0, True = 1 ], /// Privileged execute-never. PXN OFFSET(53) NUMBITS(1) [ False = 0, True = 1 ], /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] /// Access flag. AF OFFSET(10) NUMBITS(1) [ False = 0, True = 1 ], /// Shareability field. SH OFFSET(8) NUMBITS(2) [ OuterShareable = 0b10, InnerShareable = 0b11 ], /// Access Permissions. AP OFFSET(6) NUMBITS(2) [ RW_EL1 = 0b00, RW_EL1_EL0 = 0b01, RO_EL1 = 0b10, RO_EL1_EL0 = 0b11 ], /// Memory attributes index into the MAIR_EL1 register. AttrIndx OFFSET(2) NUMBITS(3) [], TYPE OFFSET(1) NUMBITS(1) [ Reserved_Invalid = 0, Page = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } /// A table descriptor for 64 KiB aperture. /// /// The output points to the next table. #[derive(Copy, Clone)] #[repr(C)] struct TableDescriptor { value: u64, } /// A page descriptor with 64 KiB aperture. /// /// The output points to physical memory. #[derive(Copy, Clone)] #[repr(C)] struct PageDescriptor { value: u64, } trait StartAddr { fn phys_start_addr_u64(&self) -> u64; fn phys_start_addr_usize(&self) -> usize; } const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB /// aligned, so the lvl3 is put first. #[repr(C)] #[repr(align(65536))] pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], } /// A translation table type for the kernel space. pub type KernelTranslationTable = FixedSizeTranslationTable; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- // The binary is still identity mapped, so we don't need to convert here. impl StartAddr for [T; N] { fn phys_start_addr_u64(&self) -> u64 { self as *const T as u64 } fn phys_start_addr_usize(&self) -> usize { self as *const _ as usize } } impl TableDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance pointing to the supplied address. pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; val.write( STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + STAGE1_TABLE_DESCRIPTOR::VALID::True, ); TableDescriptor { value: val.get() } } } /// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. impl convert::From for tock_registers::fields::FieldValue { fn from(attribute_fields: AttributeFields) -> Self { // Memory attributes. let mut desc = match attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => { STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) } MemAttributes::Device => { STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) } }; // Access Permissions. desc += match attribute_fields.acc_perms { AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, }; // The execute-never attribute is mapped to PXN in AArch64. desc += if attribute_fields.execute_never { STAGE1_PAGE_DESCRIPTOR::PXN::True } else { STAGE1_PAGE_DESCRIPTOR::PXN::False }; // Always set unprivileged exectue-never as long as userspace is not implemented yet. desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; desc } } impl PageDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance. pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; val.write( STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + STAGE1_PAGE_DESCRIPTOR::AF::True + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + STAGE1_PAGE_DESCRIPTOR::VALID::True + (*attribute_fields).into(), ); Self { value: val.get() } } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl FixedSizeTranslationTable { /// Create an instance. pub const fn new() -> Self { // Can't have a zero-sized address space. assert!(NUM_TABLES > 0); Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], } } /// Iterates over all static translation table entries and fills them at once. /// /// # Safety /// /// - Modifies a `static mut`. Ensure it only happens from here. pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { *l2_entry = TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); let (phys_output_addr, attribute_fields) = bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); } } Ok(()) } /// The translation table's base address to be used for programming the MMU. pub fn phys_base_address(&self) -> u64 { self.lvl2.phys_start_addr_u64() } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::arch_mmu use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Memory Management Unit type. struct MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; /// Constants for indexing the MAIR_EL1. #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. /// /// # Safety /// /// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); static MMU: MemoryManagementUnit = MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AddressSpace { /// Checks for architectural restrictions. pub const fn arch_address_space_size_sanity_checks() { // Size must be at least one full 512 MiB table. assert!((AS_SIZE % Granule512MiB::SIZE) == 0); // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 // version. assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } /// Configure various settings of stage 1 of the EL1 translation regime. fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the MMU instance. pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use memory::mmu::MMUEnableError; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } // Fail early if translation granule is not supported. if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } // Prepare the memory attribute indirection register. self.set_up_mair(); // Populate translation tables. KERNEL_TABLES .populate_tt_entries() .map_err(MMUEnableError::Other)?; // Set the "Translation Table Base Register". TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); self.configure_translation_control(); // Switch the MMU on. // // First, force all previous changes to be seen before the MMU is enabled. barrier::isb(barrier::SY); // Enable the MMU and turn on data and instruction caching. SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); // Force MMU init to complete before next instruction. barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/driver.rs ================================================ // 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(()) } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. use super::map as memory_map; use crate::memory::mmu::*; use core::ops::RangeInclusive; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The kernel's address space defined by this BSP. pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; const NUM_MEM_RANGES: usize = 3; /// The virtual memory layout. /// /// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. /// It is agnostic of the paging granularity that the architecture's MMU will use. pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( memory_map::END_INCLUSIVE, [ TranslationDescriptor { name: "Kernel code and RO data", virtual_range: code_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadOnly, execute_never: false, }, }, TranslationDescriptor { name: "Remapped Device MMIO", virtual_range: remapped_mmio_range_inclusive, physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), attribute_fields: AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, }, TranslationDescriptor { name: "Device MMIO", virtual_range: mmio_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, }, ], ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- fn code_range_inclusive() -> RangeInclusive { // Notice the subtraction to turn the exclusive end into an inclusive end. #[allow(clippy::range_minus_one)] RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) } fn remapped_mmio_range_inclusive() -> RangeInclusive { // The last 64 KiB slot in the first 512 MiB RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) } fn mmio_range_inclusive() -> RangeInclusive { RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the virtual memory layout. pub fn virt_mem_layout() -> &'static KernelVirtualLayout { &LAYOUT } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! //! The physical memory layout. //! //! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used //! as the boot core's stack. //! //! +---------------------------------------+ //! | | 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | //! | | pub mod mmu; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // Symbols from the linker script. extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { /// The inclusive end address of the memory map. /// /// End address + 1 must be power of two. /// /// # Note /// /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. /// /// However, making this trade-off has the downside of making it possible for the CPU to assert a /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const END_INCLUSIVE: usize = 0x4000_FFFF; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const END_INCLUSIVE: usize = 0xFF84_FFFF; } } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Start page address of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_start() -> usize { unsafe { __code_start.get() as usize } } /// Exclusive end page address of the code segment. /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_end_exclusive() -> usize { unsafe { __code_end_exclusive.get() as usize } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/bsp.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Conditional reexporting of Board Support Packages. pub mod device_driver; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use raspberrypi::*; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/common.rs ================================================ // 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") } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/exception/asynchronous.rs"] mod arch_asynchronous; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_asynchronous::print_state; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronous and asynchronous exception handling. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/exception.rs"] mod arch_exception; pub mod asynchronous; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_exception::current_privilege_level; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Kernel privilege levels. #[allow(missing_docs)] #[derive(Eq, PartialEq)] pub enum PrivilegeLevel { User, Kernel, Hypervisor, Unknown, } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![allow(incomplete_features)] #![feature(asm_const)] #![feature(const_option)] #![feature(core_intrinsics)] #![feature(format_args_nl)] #![feature(int_roundings)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_main] #![no_std] mod bsp; mod common; mod console; mod cpu; mod driver; mod exception; mod memory; mod panic_wait; mod print; mod synchronization; mod time; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order: /// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, /// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ /// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { panic!("MMU: {}", string); } // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { use console::{console, interface::Write}; use core::time::Duration; info!( "{} version {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION") ); info!("Booting on: {}", bsp::board_name()); info!("MMU online. Special regions:"); bsp::memory::mmu::virt_mem_layout().print_layout(); let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); info!("Exception handling state:"); exception::asynchronous::print_state(); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; writeln!( remapped_uart, "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" ) .unwrap(); info!("Echoing input now"); // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { let c = console().read_char(); console().write_char(c); } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Translation table. #[cfg(target_arch = "aarch64")] #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] mod arch_translation_table; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_translation_table::KernelTranslationTable; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! //! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file //! provides types for composing an architecture-agnostic description of the kernel's virtual memory //! layout. //! //! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` //! function. //! //! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and //! install respective translation tables. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; mod translation_table; use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_mmu::mmu; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// MMU enable errors variants. #[allow(missing_docs)] #[derive(Debug)] pub enum MMUEnableError { AlreadyEnabled, Other(&'static str), } /// Memory Management interfaces. pub mod interface { use super::*; /// MMU functions. pub trait MMU { /// Called by the kernel during early init. Supposed to take the translation tables from the /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. /// /// # Safety /// /// - Changes the HW's global state. unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; } } /// Describes the characteristics of a translation granule. pub struct TranslationGranule; /// Describes properties of an address space. pub struct AddressSpace; /// Architecture agnostic translation types. #[allow(missing_docs)] #[allow(dead_code)] #[derive(Copy, Clone)] pub enum Translation { Identity, Offset(usize), } /// Architecture agnostic memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum MemAttributes { CacheableDRAM, Device, } /// Architecture agnostic access permissions. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum AccessPermissions { ReadOnly, ReadWrite, } /// Collection of memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, pub execute_never: bool, } /// Architecture agnostic descriptor for a memory range. #[allow(missing_docs)] pub struct TranslationDescriptor { pub name: &'static str, pub virtual_range: fn() -> RangeInclusive, pub physical_range_translation: Translation, pub attribute_fields: AttributeFields, } /// Type for expressing the kernel's virtual memory layout. pub struct KernelVirtualLayout { /// The last (inclusive) address of the address space. max_virt_addr_inclusive: usize, /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl fmt::Display for MMUEnableError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), MMUEnableError::Other(x) => write!(f, "{}", x), } } } impl TranslationGranule { /// The granule's size. pub const SIZE: usize = Self::size_checked(); /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(GRANULE_SIZE.is_power_of_two()); GRANULE_SIZE } } impl AddressSpace { /// The address space size. pub const SIZE: usize = Self::size_checked(); /// The address space shift, aka log2(size). pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(AS_SIZE.is_power_of_two()); // Check for architectural restrictions as well. Self::arch_address_space_size_sanity_checks(); AS_SIZE } } impl Default for AttributeFields { fn default() -> AttributeFields { AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, } } } /// Human-readable output of a TranslationDescriptor. impl fmt::Display for TranslationDescriptor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Call the function to which self.range points, and dereference the result, which causes // Rust to copy the value. let start = *(self.virtual_range)().start(); let end = *(self.virtual_range)().end(); let size = end - start + 1; let (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", MemAttributes::Device => "Dev", }; let acc_p = match self.attribute_fields.acc_perms { AccessPermissions::ReadOnly => "RO", AccessPermissions::ReadWrite => "RW", }; let xn = if self.attribute_fields.execute_never { "PXN" } else { "PX" }; write!( f, " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", start, end, size, unit, attr, acc_p, xn, self.name ) } } impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { /// Create a new instance. pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { Self { max_virt_addr_inclusive: max, inner: layout, } } /// For a virtual address, find and return the physical output address and corresponding /// attributes. /// /// If the address is not found in `inner`, return an identity mapped default with normal /// cacheable DRAM attributes. pub fn virt_addr_properties( &self, virt_addr: usize, ) -> Result<(usize, AttributeFields), &'static str> { if virt_addr > self.max_virt_addr_inclusive { return Err("Address out of range"); } for i in self.inner.iter() { if (i.virtual_range)().contains(&virt_addr) { let output_addr = match i.physical_range_translation { Translation::Identity => virt_addr, Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), }; return Ok((output_addr, i.attribute_fields)); } } Ok((virt_addr, AttributeFields::default())) } /// Print the memory layout. pub fn print_layout(&self) { use crate::info; for i in self.inner.iter() { info!("{}", i); } } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management. pub mod mmu; ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", timestamp.as_secs(), timestamp.subsec_micros(), location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/src/time.rs ================================================ // 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) } } ================================================ FILE: 10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 11_exceptions_part1_groundwork/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 11_exceptions_part1_groundwork/Cargo.toml ================================================ [package] name = "mingo" version = "0.11.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: 11_exceptions_part1_groundwork/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: 11_exceptions_part1_groundwork/README.md ================================================ # Tutorial 11 - Exceptions Part 1: Groundwork ## tl;dr - We lay the groundwork for all the architectural `CPU exceptions`. - For now, only print an elaborate system state through a `panic!` call, and halt execution - This will help finding bugs during development and runtime. - For demo purposes, MMU `page faults` are used to demonstrate (i) returning from an exception and (ii) the default `panic!` behavior. ## Table of Contents - [Introduction](#introduction) - [Exception Types](#exception-types) - [Exception entry](#exception-entry) * [Exception Vectors](#exception-vectors) - [Handler Code and Offsets](#handler-code-and-offsets) - [Rust and Assembly Implementation](#rust-and-assembly-implementation) * [Context Save and Restore](#context-save-and-restore) * [Exception Vector Table](#exception-vector-table) * [Implementing handlers](#implementing-handlers) - [Causing an Exception - Testing the Code](#causing-an-exception---testing-the-code) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction Now that we are executing in `EL1`, and have activated the `MMU`, time is due for implementing `CPU exceptions`. For now, we only set up a scaffold with very basic functionality that will help us to find bugs along the way. A follow-up `Interrupt` tutorial later will continue the work we start here. Please note that this tutorial is specific to the `AArch64` architecture. It does not contain any generic exception handling code yet. ## Exception Types In `AArch64`, it is differentiated between four types of exceptions. These are: - Synchronous - For example, a `data abort` (e.g. `page fault`) or a `system call`. They happen in direct consequence of executing a certain CPU instruction, hence _synchronously_. - Interrupt Request (`IRQ`) - For example, an external device, like a timer, is asserting a physical interrupt line. IRQs happen _asynchronously_. - Fast Interrupt Request (`FIQ`) - These are basically interrupts that take priority over normal IRQs and have some more traits that make them suitable to implement super-fast processing. However, this is out of scope for this tutorial. For the sake of keeping these tutorials compact and concise, we will more or less ignore FIQs and only implement a dummy handler that would halt the CPU core. - System Error (`SError`) - Like IRQs, SErrors happen asynchronously and are technically more or less the same. They are intended to signal rather fatal errors in the system, e.g. if a transaction times out on the `SoC` interconnect. They are very implementation specific and it is up to the SoC vendor to decide which events are delivered as SErrors instead of normal IRQs. ## Exception entry I recommend to read pages D1-5355 of the [ARMv8 Architecture Reference Manual][ARMv8_Manual Ja] to understand the mechanisms of taking an exception. Here's an excerpt of important features for this tutorial: - Exception entry moves the processor to the same or a higher `Exception Level`, but never to a lower `EL`. - The program status is saved in the `SPSR_ELx` register at the target `EL`. - The preferred return address is saved in the `ELR_ELx` register. - "Preferred" here means that `ELR_ELx` may hold the instruction address of the instructions that caused the exception (`synchronous case`) or the first instruction that did not complete due to an `asynchronous` exception. Details in pages D1-5357 of the [ARMv8 Architecture Reference Manual][ARMv8_Manual Ja]. - All kinds of exceptions are turned off upon taking an exception, so that by default, exception handlers can not get interrupted themselves. - Taking an exception will select the dedicated stack pointer of the target `EL`. - For example, if an exception in `EL0` is taken, the Stack Pointer Select register `SPSel` will switch from `0` to `1`, meaning that `SP_EL1` will be used by the exception vector code unless you explicitly change it back to `SP_EL0`. ### Exception Vectors `AArch64` has a total of `16` exception vectors. There is one for each of the four kinds that were introduced already, and additionally, it is taken into account _where_ the exception was taken from and what the circumstances were. Here is a copy of the decision table as shown in pages D1-5358 of the [ARMv8 Architecture Reference Manual][ARMv8_Manual Ja]: [ARMv8_Manual Ja]: https://developer.arm.com/documentation/ddi0487/ja/
Exception taken from Offset for exception type
Synchronous IRQ or vIRQ FIQ or vFIQ SError or vSError
Current Exception level with SP_EL0. 0x000 0x080 0x100 0x180
Current Exception level with SP_ELx, x>0. 0x200 0x280 0x300 0x380
Lower Exception level, where the implemented level immediately lower than the target level is using AArch64. 0x400 0x480 0x500 0x580
Lower Exception level, where the implemented level immediately lower than the target level is using AArch32. 0x600 0x680 0x700 0x780
Since our kernel runs in `EL1`, using `SP_EL1`, if we'd cause a synchronous exception, the exception vector at offset `0x200` would be executed. But what does that even mean? ## Handler Code and Offsets In many architectures, Operating Systems register their exception handlers (aka vectors) by compiling an architecturally defined data structure that stores function pointers to the different handlers. This can be as simple as an ordinary array of function pointers. The `base address` of this data structure is then stored into a special purpose register so that the CPU can branch to the respective handler function upon taking an exception. The classic `x86_64` architecture follows this principle, for example. In `AArch64`, it is a bit different. Here, we have the special purpose register as well, called `VBAR_EL1`: Vector Base Address Register. However, it does not store the base address of an array of function pointers, but the base address of a **memory location that contains code** for the 16 handlers, one handler back-to-back after the other. Each handler can take a maximum space of `0x80` bytes, aka `128` bytes. That's why the table above shows `offsets`: To indicate at which offset a certain handler starts. Of course, you are not obliged to cram all your handler code into only 128 bytes. You are free to branch off to any other functions at any time. Actually, that is needed in most cases anyways, because the context-saving code alone would take up most of the available space (you'll learn what context saving is shortly). Additionally, there is a requirement that the `Vector Base Address` is aligned to `0x800` aka `2048` bytes. ## Rust and Assembly Implementation The implementation uses a mix of `Rust` and `Assembly` code. ### Context Save and Restore Exception vectors, just like any other code, use a bunch of commonly shared processor resources. Most of all, the set of `General Purpose Registers` (GPRs) that each core in `AArch64` provides (`x0`-`x30`). In order to not taint these registers when executing exception vector code, it is general practice to save these shared resources in memory (the stack, to be precise) as the very first action. This is commonly described as *saving the context*. Exception vector code can then use the shared resources in its own code without bothering, and as a last action before returning from exception handling code, restore the context, so that the processor can continue where it left off before taking the exception. Context save and restore is one of the few places in system software where there is no way around some hand-crafted assembly. Introducing `exception.s`: ```asm /// Call the function provided by parameter `\handler` after saving the exception context. Provide /// the context as the first parameter to '\handler'. .macro CALL_WITH_CONTEXT handler __vector_\handler: // Make room on the stack for the exception context. sub sp, sp, #16 * 17 // Store all general purpose registers on the stack. stp x0, x1, [sp, #16 * 0] stp x2, x3, [sp, #16 * 1] stp x4, x5, [sp, #16 * 2] stp x6, x7, [sp, #16 * 3] stp x8, x9, [sp, #16 * 4] stp x10, x11, [sp, #16 * 5] stp x12, x13, [sp, #16 * 6] stp x14, x15, [sp, #16 * 7] stp x16, x17, [sp, #16 * 8] stp x18, x19, [sp, #16 * 9] stp x20, x21, [sp, #16 * 10] stp x22, x23, [sp, #16 * 11] stp x24, x25, [sp, #16 * 12] stp x26, x27, [sp, #16 * 13] stp x28, x29, [sp, #16 * 14] // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception // syndrome register (ESR_EL1). mrs x1, ELR_EL1 mrs x2, SPSR_EL1 mrs x3, ESR_EL1 stp lr, x1, [sp, #16 * 15] stp x2, x3, [sp, #16 * 16] // x0 is the first argument for the function called through `\handler`. mov x0, sp // Call `\handler`. bl \handler // After returning from exception handling code, replay the saved context and return via // `eret`. b __exception_restore_context .size __vector_\handler, . - __vector_\handler .type __vector_\handler, function .endm ``` First, a macro for saving the context is defined. It eventually jumps to follow-up handler code, and finally restores the context. In advance, we reserve space on the stack for the context. That is, the 30 `GPRs`, the `link register`, the `exception link register` (holding the preferred return address), the `saved program status` and the `exception syndrome register`. Afterwards, we store those registers, save the current stack address in `x0` and branch off to follow-up handler-code, whose function name is supplied as an argument to the macro (`\handler`). The handler code will be written in Rust, but use the platform's `C` ABI. This way, we can define a function signature that has a pointer to the context-data on the stack as its first argument, and know that this argument is expected to be in the `x0` register. We need to use the `C` ABI here because `Rust` has no stable convention ([yet](https://github.com/rust-lang/rfcs/issues/600)). ### Exception Vector Table Next, we craft the exception vector table: ```asm // Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. .align 11 // Export a symbol for the Rust code to use. __exception_vector_start: // Current exception level with SP_EL0. // // .org sets the offset relative to section start. // // # Safety // // - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. .org 0x000 CALL_WITH_CONTEXT current_el0_synchronous .org 0x080 CALL_WITH_CONTEXT current_el0_irq .org 0x100 FIQ_SUSPEND .org 0x180 CALL_WITH_CONTEXT current_el0_serror // Current exception level with SP_ELx, x > 0. .org 0x200 CALL_WITH_CONTEXT current_elx_synchronous .org 0x280 CALL_WITH_CONTEXT current_elx_irq .org 0x300 FIQ_SUSPEND .org 0x380 CALL_WITH_CONTEXT current_elx_serror [...] ``` Note how each vector starts at the required offset from the section start using the `.org` directive. Each macro call introduces an explicit handler function name, which is implemented in `Rust` in `exception.rs`. ### Implementing handlers The file `exception.rs` first defines a `struct` of the exception context that is stored on the stack by the assembly code: ```rust /// The exception context as it is stored on the stack on exception entry. #[repr(C)] struct ExceptionContext { /// General Purpose Registers. gpr: [u64; 30], /// The link register, aka x30. lr: u64, /// Exception link register. The program counter at the time the exception happened. elr_el1: u64, /// Saved program status. spsr_el1: SpsrEL1, // Exception syndrome register. esr_el1: EsrEL1, } ``` The handlers take a `struct ExceptionContext` argument. Since we do not plan to implement handlers for each exception yet, a default handler is provided: ```rust /// Prints verbose information about the exception and then panics. fn default_exception_handler(exc: &ExceptionContext) { panic!( "CPU Exception!\n\n\ {}", exc ); } ``` The actual handlers referenced from the assembly can now branch to it for the time being, e.g.: ```rust #[no_mangle] extern "C" fn current_elx_irq(e: &mut ExceptionContext) { default_exception_handler(e); } ``` ## Causing an Exception - Testing the Code We want to see two cases in action: 1. How taking, handling and returning from an exception works. 2. How the `panic!` print for unhandled exceptions looks like. So after setting up exceptions in `main.rs` by calling ```rust exception::handling_init(); ``` we cause a data abort exception by reading from memory address `8 GiB`: ```rust // Cause an exception by accessing a virtual address for which no translation was set up. This // code accesses the address 8 GiB, which is outside the mapped address space. // // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow // execution to continue. info!(""); info!("Trying to read from address 8 GiB..."); let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; ``` This triggers our exception code, because we try to read from a virtual address for which no mapping has been installed. Remember, we only mapped up to `4 GiB` of address space in the previous tutorial. To survive this exception, the respective handler has a special demo case: ```rust #[no_mangle] extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { if e.fault_address_valid() { let far_el1 = FAR_EL1.get(); // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, // advance the exception link register for one instruction, so that execution can continue. if far_el1 == 8 * 1024 * 1024 * 1024 { e.elr_el1 += 4; return; } } default_exception_handler(e); } ``` It checks if the faulting address equals `8 GiB`, and if so, advances the copy of the `ELR` by 4, which makes it point to the next instruction after the instruction that caused the exception. When this handler returns, execution continues in the assembly macro we introduced before. The macro has only one more line left: `b __exception_restore_context`, which jumps to an assembly function that plays back our saved context before finally executing `eret` to return from the exception. This will kick us back into `main.rs`. But we also want to see the `panic!` print. Therefore, a second read is done, this time from address `9 GiB`. A case which the handler will not catch, eventually triggering the `panic!` call from the default handler. ## Test it ```console $ make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 64 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.798323] mingo version 0.11.0 [ 0.798530] Booting on: Raspberry Pi 3 [ 0.798985] MMU online. Special regions: [ 0.799462] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data [ 0.800480] 0x3f000000 - 0x4000ffff | 17 MiB | Dev RW PXN | Device MMIO [ 0.801369] Current privilege level: EL1 [ 0.801845] Exception handling state: [ 0.802290] Debug: Masked [ 0.802680] SError: Masked [ 0.803069] IRQ: Masked [ 0.803459] FIQ: Masked [ 0.803849] Architectural timer resolution: 52 ns [ 0.804423] Drivers loaded: [ 0.804759] 1. BCM PL011 UART [ 0.805182] 2. BCM GPIO [ 0.805539] Timer test, spinning for 1 second [ 1.806070] [ 1.806074] Trying to read from address 8 GiB... [ 1.806624] ************************************************ [ 1.807316] Whoa! We recovered from a synchronous exception! [ 1.808009] ************************************************ [ 1.808703] [ 1.808876] Let's try again [ 1.809212] Trying to read from address 9 GiB... [ 1.809776] Kernel panic! Panic location: File 'src/_arch/aarch64/exception.rs', line 58, column 5 CPU Exception! ESR_EL1: 0x96000004 Exception Class (EC) : 0x25 - Data Abort, current EL Instr Specific Syndrome (ISS): 0x4 FAR_EL1: 0x0000000240000000 SPSR_EL1: 0x600003c5 Flags: Negative (N): Not set Zero (Z): Set Carry (C): Set Overflow (V): Not set Exception handling state: Debug (D): Masked SError (A): Masked IRQ (I): Masked FIQ (F): Masked Illegal Execution State (IL): Not set ELR_EL1: 0x00000000000845f8 General purpose register: x0 : 0x0000000000000000 x1 : 0x0000000000086187 x2 : 0x0000000000000027 x3 : 0x0000000000081280 x4 : 0x0000000000000006 x5 : 0x1e27329c00000000 x6 : 0x0000000000000000 x7 : 0xd3d18908028f0243 x8 : 0x0000000240000000 x9 : 0x0000000000086187 x10: 0x0000000000000443 x11: 0x000000003f201000 x12: 0x0000000000000019 x13: 0x00000000ffffd8f0 x14: 0x000000000000147b x15: 0x00000000ffffff9c x16: 0x000000000007fd38 x17: 0x0000000005f5e0ff x18: 0x00000000000c58fc x19: 0x0000000000090008 x20: 0x0000000000085fc0 x21: 0x000000003b9aca00 x22: 0x0000000000082238 x23: 0x00000000000813d4 x24: 0x0000000010624dd3 x25: 0xffffffffc4653600 x26: 0x0000000000086988 x27: 0x0000000000086080 x28: 0x0000000000085f10 x29: 0x0000000000085c00 lr : 0x00000000000845ec ``` ## Diff to previous ```diff diff -uNr 10_virtual_mem_part1_identity_mapping/Cargo.toml 11_exceptions_part1_groundwork/Cargo.toml --- 10_virtual_mem_part1_identity_mapping/Cargo.toml +++ 11_exceptions_part1_groundwork/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.10.0" +version = "0.11.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs --- 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.rs +++ 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs @@ -11,8 +11,263 @@ //! //! crate::exception::arch_exception -use aarch64_cpu::registers::*; -use tock_registers::interfaces::Readable; +use aarch64_cpu::{asm::barrier, registers::*}; +use core::{arch::global_asm, cell::UnsafeCell, fmt}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + registers::InMemoryRegister, +}; + +// Assembly counterpart to this file. +global_asm!(include_str!("exception.s")); + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper structs for memory copies of registers. +#[repr(transparent)] +struct SpsrEL1(InMemoryRegister); +struct EsrEL1(InMemoryRegister); + +/// The exception context as it is stored on the stack on exception entry. +#[repr(C)] +struct ExceptionContext { + /// General Purpose Registers. + gpr: [u64; 30], + + /// The link register, aka x30. + lr: u64, + + /// Exception link register. The program counter at the time the exception happened. + elr_el1: u64, + + /// Saved program status. + spsr_el1: SpsrEL1, + + /// Exception syndrome register. + esr_el1: EsrEL1, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +/// Prints verbose information about the exception and then panics. +fn default_exception_handler(exc: &ExceptionContext) { + panic!( + "CPU Exception!\n\n\ + {}", + exc + ); +} + +//------------------------------------------------------------------------------ +// Current, EL0 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +#[no_mangle] +extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { + panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") +} + +//------------------------------------------------------------------------------ +// Current, ELx +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { + if e.fault_address_valid() { + let far_el1 = FAR_EL1.get(); + + // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, + // advance the exception link register for one instruction, so that execution can continue. + if far_el1 == 8 * 1024 * 1024 * 1024 { + e.elr_el1 += 4; + + return; + } + } + + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn current_elx_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch64 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Lower, AArch32 +//------------------------------------------------------------------------------ + +#[no_mangle] +extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +#[no_mangle] +extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { + default_exception_handler(e); +} + +//------------------------------------------------------------------------------ +// Misc +//------------------------------------------------------------------------------ + +/// Human readable SPSR_EL1. +#[rustfmt::skip] +impl fmt::Display for SpsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw value. + writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; + + let to_flag_str = |x| -> _ { + if x { "Set" } else { "Not set" } + }; + + writeln!(f, " Flags:")?; + writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; + writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; + writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; + writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; + + let to_mask_str = |x| -> _ { + if x { "Masked" } else { "Unmasked" } + }; + + writeln!(f, " Exception handling state:")?; + writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; + writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; + writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; + writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; + + write!(f, " Illegal Execution State (IL): {}", + to_flag_str(self.0.is_set(SPSR_EL1::IL)) + ) + } +} + +impl EsrEL1 { + #[inline(always)] + fn exception_class(&self) -> Option { + self.0.read_as_enum(ESR_EL1::EC) + } +} + +/// Human readable ESR_EL1. +#[rustfmt::skip] +impl fmt::Display for EsrEL1 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Raw print of whole register. + writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; + + // Raw print of exception class. + write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; + + // Exception class. + let ec_translation = match self.exception_class() { + Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", + _ => "N/A", + }; + writeln!(f, " - {}", ec_translation)?; + + // Raw print of instruction specific syndrome. + write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) + } +} + +impl ExceptionContext { + #[inline(always)] + fn exception_class(&self) -> Option { + self.esr_el1.exception_class() + } + + #[inline(always)] + fn fault_address_valid(&self) -> bool { + use ESR_EL1::EC::Value::*; + + match self.exception_class() { + None => false, + Some(ec) => matches!( + ec, + InstrAbortLowerEL + | InstrAbortCurrentEL + | PCAlignmentFault + | DataAbortLowerEL + | DataAbortCurrentEL + | WatchpointLowerEL + | WatchpointCurrentEL + ), + } + } +} + +/// Human readable print of the exception context. +impl fmt::Display for ExceptionContext { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + writeln!(f, "{}", self.esr_el1)?; + + if self.fault_address_valid() { + writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; + } + + writeln!(f, "{}", self.spsr_el1)?; + writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; + writeln!(f)?; + writeln!(f, "General purpose register:")?; + + #[rustfmt::skip] + let alternating = |x| -> _ { + if x modulo 2 == 0 { " " } else { "\n" } + }; + + // Print two registers per line. + for (i, reg) in self.gpr.iter().enumerate() { + write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; + } + write!(f, " lr : {:#018x}", self.lr) + } +} //-------------------------------------------------------------------------------------------------- // Public Code @@ -29,3 +284,23 @@ _ => (PrivilegeLevel::Unknown, "Unknown"), } } + +/// Init exception handling by setting the exception vector base address register. +/// +/// # Safety +/// +/// - Changes the HW state of the executing core. +/// - The vector table and the symbol `__exception_vector_table_start` from the linker script must +/// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference +/// Manual. +pub unsafe fn handling_init() { + // Provided by exception.S. + extern "Rust" { + static __exception_vector_start: UnsafeCell<()>; + } + + VBAR_EL1.set(__exception_vector_start.get() as u64); + + // Force VBAR update to complete before next instruction. + barrier::isb(barrier::SY); +} diff -uNr 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.s 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s --- 10_virtual_mem_part1_identity_mapping/src/_arch/aarch64/exception.s +++ 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s @@ -0,0 +1,154 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//-------------------------------------------------------------------------------------------------- +// Definitions +//-------------------------------------------------------------------------------------------------- + +/// Call the function provided by parameter `\handler` after saving the exception context. Provide +/// the context as the first parameter to '\handler'. +.macro CALL_WITH_CONTEXT handler +__vector_\handler: + // Make room on the stack for the exception context. + sub sp, sp, #16 * 17 + + // Store all general purpose registers on the stack. + stp x0, x1, [sp, #16 * 0] + stp x2, x3, [sp, #16 * 1] + stp x4, x5, [sp, #16 * 2] + stp x6, x7, [sp, #16 * 3] + stp x8, x9, [sp, #16 * 4] + stp x10, x11, [sp, #16 * 5] + stp x12, x13, [sp, #16 * 6] + stp x14, x15, [sp, #16 * 7] + stp x16, x17, [sp, #16 * 8] + stp x18, x19, [sp, #16 * 9] + stp x20, x21, [sp, #16 * 10] + stp x22, x23, [sp, #16 * 11] + stp x24, x25, [sp, #16 * 12] + stp x26, x27, [sp, #16 * 13] + stp x28, x29, [sp, #16 * 14] + + // Add the exception link register (ELR_EL1), saved program status (SPSR_EL1) and exception + // syndrome register (ESR_EL1). + mrs x1, ELR_EL1 + mrs x2, SPSR_EL1 + mrs x3, ESR_EL1 + + stp lr, x1, [sp, #16 * 15] + stp x2, x3, [sp, #16 * 16] + + // x0 is the first argument for the function called through `\handler`. + mov x0, sp + + // Call `\handler`. + bl \handler + + // After returning from exception handling code, replay the saved context and return via + // `eret`. + b __exception_restore_context + +.size __vector_\handler, . - __vector_\handler +.type __vector_\handler, function +.endm + +.macro FIQ_SUSPEND +1: wfe + b 1b +.endm + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +.section .text + +//------------------------------------------------------------------------------ +// The exception vector table. +//------------------------------------------------------------------------------ + +// Align by 2^11 bytes, as demanded by ARMv8-A. Same as ALIGN(2048) in an ld script. +.align 11 + +// Export a symbol for the Rust code to use. +__exception_vector_start: + +// Current exception level with SP_EL0. +// +// .org sets the offset relative to section start. +// +// # Safety +// +// - It must be ensured that `CALL_WITH_CONTEXT` <= 0x80 bytes. +.org 0x000 + CALL_WITH_CONTEXT current_el0_synchronous +.org 0x080 + CALL_WITH_CONTEXT current_el0_irq +.org 0x100 + FIQ_SUSPEND +.org 0x180 + CALL_WITH_CONTEXT current_el0_serror + +// Current exception level with SP_ELx, x > 0. +.org 0x200 + CALL_WITH_CONTEXT current_elx_synchronous +.org 0x280 + CALL_WITH_CONTEXT current_elx_irq +.org 0x300 + FIQ_SUSPEND +.org 0x380 + CALL_WITH_CONTEXT current_elx_serror + +// Lower exception level, AArch64 +.org 0x400 + CALL_WITH_CONTEXT lower_aarch64_synchronous +.org 0x480 + CALL_WITH_CONTEXT lower_aarch64_irq +.org 0x500 + FIQ_SUSPEND +.org 0x580 + CALL_WITH_CONTEXT lower_aarch64_serror + +// Lower exception level, AArch32 +.org 0x600 + CALL_WITH_CONTEXT lower_aarch32_synchronous +.org 0x680 + CALL_WITH_CONTEXT lower_aarch32_irq +.org 0x700 + FIQ_SUSPEND +.org 0x780 + CALL_WITH_CONTEXT lower_aarch32_serror +.org 0x800 + +//------------------------------------------------------------------------------ +// fn __exception_restore_context() +//------------------------------------------------------------------------------ +__exception_restore_context: + ldr w19, [sp, #16 * 16] + ldp lr, x20, [sp, #16 * 15] + + msr SPSR_EL1, x19 + msr ELR_EL1, x20 + + ldp x0, x1, [sp, #16 * 0] + ldp x2, x3, [sp, #16 * 1] + ldp x4, x5, [sp, #16 * 2] + ldp x6, x7, [sp, #16 * 3] + ldp x8, x9, [sp, #16 * 4] + ldp x10, x11, [sp, #16 * 5] + ldp x12, x13, [sp, #16 * 6] + ldp x14, x15, [sp, #16 * 7] + ldp x16, x17, [sp, #16 * 8] + ldp x18, x19, [sp, #16 * 9] + ldp x20, x21, [sp, #16 * 10] + ldp x22, x23, [sp, #16 * 11] + ldp x24, x25, [sp, #16 * 12] + ldp x26, x27, [sp, #16 * 13] + ldp x28, x29, [sp, #16 * 14] + + add sp, sp, #16 * 17 + + eret + +.size __exception_restore_context, . - __exception_restore_context +.type __exception_restore_context, function diff -uNr 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs --- 10_virtual_mem_part1_identity_mapping/src/bsp/raspberrypi/memory/mmu.rs +++ 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs @@ -15,7 +15,7 @@ /// The kernel's address space defined by this BSP. pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; -const NUM_MEM_RANGES: usize = 3; +const NUM_MEM_RANGES: usize = 2; /// The virtual memory layout. /// @@ -35,16 +35,6 @@ }, }, TranslationDescriptor { - name: "Remapped Device MMIO", - virtual_range: remapped_mmio_range_inclusive, - physical_range_translation: Translation::Offset(memory_map::mmio::START + 0x20_0000), - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - }, - TranslationDescriptor { name: "Device MMIO", virtual_range: mmio_range_inclusive, physical_range_translation: Translation::Identity, @@ -67,11 +57,6 @@ RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) } -fn remapped_mmio_range_inclusive() -> RangeInclusive { - // The last 64 KiB slot in the first 512 MiB - RangeInclusive::new(0x1FFF_0000, 0x1FFF_FFFF) -} - fn mmio_range_inclusive() -> RangeInclusive { RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) } diff -uNr 10_virtual_mem_part1_identity_mapping/src/bsp.rs 11_exceptions_part1_groundwork/src/bsp.rs --- 10_virtual_mem_part1_identity_mapping/src/bsp.rs +++ 11_exceptions_part1_groundwork/src/bsp.rs @@ -4,7 +4,7 @@ //! Conditional reexporting of Board Support Packages. -pub mod device_driver; +mod device_driver; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod raspberrypi; diff -uNr 10_virtual_mem_part1_identity_mapping/src/exception.rs 11_exceptions_part1_groundwork/src/exception.rs --- 10_virtual_mem_part1_identity_mapping/src/exception.rs +++ 11_exceptions_part1_groundwork/src/exception.rs @@ -13,7 +13,7 @@ //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- -pub use arch_exception::current_privilege_level; +pub use arch_exception::{current_privilege_level, handling_init}; //-------------------------------------------------------------------------------------------------- // Public Definitions diff -uNr 10_virtual_mem_part1_identity_mapping/src/main.rs 11_exceptions_part1_groundwork/src/main.rs --- 10_virtual_mem_part1_identity_mapping/src/main.rs +++ 11_exceptions_part1_groundwork/src/main.rs @@ -144,6 +144,8 @@ unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; + exception::handling_init(); + if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { panic!("MMU: {}", string); } @@ -163,7 +165,7 @@ /// The main function running after the early init. fn kernel_main() -> ! { - use console::{console, interface::Write}; + use console::console; use core::time::Duration; info!( @@ -193,13 +195,28 @@ info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); - let remapped_uart = unsafe { bsp::device_driver::PL011Uart::new(0x1FFF_1000) }; - writeln!( - remapped_uart, - "[ !!! ] Writing through the remapped UART at 0x1FFF_1000" - ) - .unwrap(); + // Cause an exception by accessing a virtual address for which no translation was set up. This + // code accesses the address 8 GiB, which is outside the mapped address space. + // + // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow + // execution to continue. + info!(""); + info!("Trying to read from address 8 GiB..."); + let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; + unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; + + info!("************************************************"); + info!("Whoa! We recovered from a synchronous exception!"); + info!("************************************************"); + info!(""); + info!("Let's try again"); + + // Now use address 9 GiB. The exception handler won't forgive us this time. + info!("Trying to read from address 9 GiB..."); + big_addr = 9 * 1024 * 1024 * 1024; + unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; + // Will never reach here in this tutorial. info!("Echoing input now"); // Discard any spurious received characters before going into echo mode. diff -uNr 10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb 11_exceptions_part1_groundwork/tests/boot_test_string.rb --- 10_virtual_mem_part1_identity_mapping/tests/boot_test_string.rb +++ 11_exceptions_part1_groundwork/tests/boot_test_string.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -EXPECTED_PRINT = 'Echoing input now' +EXPECTED_PRINT = 'lr : 0x' ``` ================================================ FILE: 11_exceptions_part1_groundwork/build.rs ================================================ 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())); } ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prepares the transition from EL2 to EL1. /// /// # Safety /// /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. /// /// # Safety /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. x0 holds the function argument provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/cpu.rs ================================================ // 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() } } ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::asynchronous::arch_asynchronous use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- trait DaifField { fn daif_field() -> tock_registers::fields::Field; } struct Debug; struct SError; struct IRQ; struct FIQ; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl DaifField for Debug { fn daif_field() -> tock_registers::fields::Field { DAIF::D } } impl DaifField for SError { fn daif_field() -> tock_registers::fields::Field { DAIF::A } } impl DaifField for IRQ { fn daif_field() -> tock_registers::fields::Field { DAIF::I } } impl DaifField for FIQ { fn daif_field() -> tock_registers::fields::Field { DAIF::F } } fn is_masked() -> bool where T: DaifField, { DAIF.is_set(T::daif_field()) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Print the AArch64 exceptions status. #[rustfmt::skip] pub fn print_state() { use crate::info; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; info!(" Debug: {}", to_mask_str(is_masked::())); info!(" SError: {}", to_mask_str(is_masked::())); info!(" IRQ: {}", to_mask_str(is_masked::())); info!(" FIQ: {}", to_mask_str(is_masked::())); } ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::arch_exception use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::InMemoryRegister, }; // Assembly counterpart to this file. global_asm!(include_str!("exception.s")); //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Wrapper structs for memory copies of registers. #[repr(transparent)] struct SpsrEL1(InMemoryRegister); struct EsrEL1(InMemoryRegister); /// The exception context as it is stored on the stack on exception entry. #[repr(C)] struct ExceptionContext { /// General Purpose Registers. gpr: [u64; 30], /// The link register, aka x30. lr: u64, /// Exception link register. The program counter at the time the exception happened. elr_el1: u64, /// Saved program status. spsr_el1: SpsrEL1, /// Exception syndrome register. esr_el1: EsrEL1, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prints verbose information about the exception and then panics. fn default_exception_handler(exc: &ExceptionContext) { panic!( "CPU Exception!\n\n\ {}", exc ); } //------------------------------------------------------------------------------ // Current, EL0 //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } #[no_mangle] extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } #[no_mangle] extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } //------------------------------------------------------------------------------ // Current, ELx //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { if e.fault_address_valid() { let far_el1 = FAR_EL1.get(); // This catches the demo case for this tutorial. If the fault address happens to be 8 GiB, // advance the exception link register for one instruction, so that execution can continue. if far_el1 == 8 * 1024 * 1024 * 1024 { e.elr_el1 += 4; return; } } default_exception_handler(e); } #[no_mangle] extern "C" fn current_elx_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } //------------------------------------------------------------------------------ // Lower, AArch64 //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } //------------------------------------------------------------------------------ // Lower, AArch32 //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } //------------------------------------------------------------------------------ // Misc //------------------------------------------------------------------------------ /// Human readable SPSR_EL1. #[rustfmt::skip] impl fmt::Display for SpsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Raw value. writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; let to_flag_str = |x| -> _ { if x { "Set" } else { "Not set" } }; writeln!(f, " Flags:")?; writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; writeln!(f, " Exception handling state:")?; writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; write!(f, " Illegal Execution State (IL): {}", to_flag_str(self.0.is_set(SPSR_EL1::IL)) ) } } impl EsrEL1 { #[inline(always)] fn exception_class(&self) -> Option { self.0.read_as_enum(ESR_EL1::EC) } } /// Human readable ESR_EL1. #[rustfmt::skip] impl fmt::Display for EsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Raw print of whole register. writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; // Raw print of exception class. write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; // Exception class. let ec_translation = match self.exception_class() { Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", _ => "N/A", }; writeln!(f, " - {}", ec_translation)?; // Raw print of instruction specific syndrome. write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) } } impl ExceptionContext { #[inline(always)] fn exception_class(&self) -> Option { self.esr_el1.exception_class() } #[inline(always)] fn fault_address_valid(&self) -> bool { use ESR_EL1::EC::Value::*; match self.exception_class() { None => false, Some(ec) => matches!( ec, InstrAbortLowerEL | InstrAbortCurrentEL | PCAlignmentFault | DataAbortLowerEL | DataAbortCurrentEL | WatchpointLowerEL | WatchpointCurrentEL ), } } } /// Human readable print of the exception context. impl fmt::Display for ExceptionContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{}", self.esr_el1)?; if self.fault_address_valid() { writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; } writeln!(f, "{}", self.spsr_el1)?; writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; writeln!(f)?; writeln!(f, "General purpose register:")?; #[rustfmt::skip] let alternating = |x| -> _ { if x % 2 == 0 { " " } else { "\n" } }; // Print two registers per line. for (i, reg) in self.gpr.iter().enumerate() { write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; } write!(f, " lr : {:#018x}", self.lr) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use crate::exception::PrivilegeLevel; /// The processing element's current privilege level. pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { let el = CurrentEL.read_as_enum(CurrentEL::EL); match el { Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), _ => (PrivilegeLevel::Unknown, "Unknown"), } } /// Init exception handling by setting the exception vector base address register. /// /// # Safety /// /// - Changes the HW state of the executing core. /// - The vector table and the symbol `__exception_vector_table_start` from the linker script must /// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference /// Manual. pub unsafe fn handling_init() { // Provided by exception.S. extern "Rust" { static __exception_vector_start: UnsafeCell<()>; } VBAR_EL1.set(__exception_vector_start.get() as u64); // Force VBAR update to complete before next instruction. barrier::isb(barrier::SY); } ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::translation_table::arch_translation_table use crate::{ bsp, memory, memory::mmu::{ arch_mmu::{Granule512MiB, Granule64KiB}, AccessPermissions, AttributeFields, MemAttributes, }, }; use core::convert; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, registers::InMemoryRegister, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. register_bitfields! {u64, STAGE1_TABLE_DESCRIPTOR [ /// Physical address of the next descriptor. NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] TYPE OFFSET(1) NUMBITS(1) [ Block = 0, Table = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } // A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. register_bitfields! {u64, STAGE1_PAGE_DESCRIPTOR [ /// Unprivileged execute-never. UXN OFFSET(54) NUMBITS(1) [ False = 0, True = 1 ], /// Privileged execute-never. PXN OFFSET(53) NUMBITS(1) [ False = 0, True = 1 ], /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] /// Access flag. AF OFFSET(10) NUMBITS(1) [ False = 0, True = 1 ], /// Shareability field. SH OFFSET(8) NUMBITS(2) [ OuterShareable = 0b10, InnerShareable = 0b11 ], /// Access Permissions. AP OFFSET(6) NUMBITS(2) [ RW_EL1 = 0b00, RW_EL1_EL0 = 0b01, RO_EL1 = 0b10, RO_EL1_EL0 = 0b11 ], /// Memory attributes index into the MAIR_EL1 register. AttrIndx OFFSET(2) NUMBITS(3) [], TYPE OFFSET(1) NUMBITS(1) [ Reserved_Invalid = 0, Page = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } /// A table descriptor for 64 KiB aperture. /// /// The output points to the next table. #[derive(Copy, Clone)] #[repr(C)] struct TableDescriptor { value: u64, } /// A page descriptor with 64 KiB aperture. /// /// The output points to physical memory. #[derive(Copy, Clone)] #[repr(C)] struct PageDescriptor { value: u64, } trait StartAddr { fn phys_start_addr_u64(&self) -> u64; fn phys_start_addr_usize(&self) -> usize; } const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB /// aligned, so the lvl3 is put first. #[repr(C)] #[repr(align(65536))] pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], } /// A translation table type for the kernel space. pub type KernelTranslationTable = FixedSizeTranslationTable; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- // The binary is still identity mapped, so we don't need to convert here. impl StartAddr for [T; N] { fn phys_start_addr_u64(&self) -> u64 { self as *const T as u64 } fn phys_start_addr_usize(&self) -> usize { self as *const _ as usize } } impl TableDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance pointing to the supplied address. pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; val.write( STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + STAGE1_TABLE_DESCRIPTOR::VALID::True, ); TableDescriptor { value: val.get() } } } /// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. impl convert::From for tock_registers::fields::FieldValue { fn from(attribute_fields: AttributeFields) -> Self { // Memory attributes. let mut desc = match attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => { STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) } MemAttributes::Device => { STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) } }; // Access Permissions. desc += match attribute_fields.acc_perms { AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, }; // The execute-never attribute is mapped to PXN in AArch64. desc += if attribute_fields.execute_never { STAGE1_PAGE_DESCRIPTOR::PXN::True } else { STAGE1_PAGE_DESCRIPTOR::PXN::False }; // Always set unprivileged exectue-never as long as userspace is not implemented yet. desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; desc } } impl PageDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance. pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; val.write( STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + STAGE1_PAGE_DESCRIPTOR::AF::True + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + STAGE1_PAGE_DESCRIPTOR::VALID::True + (*attribute_fields).into(), ); Self { value: val.get() } } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl FixedSizeTranslationTable { /// Create an instance. pub const fn new() -> Self { // Can't have a zero-sized address space. assert!(NUM_TABLES > 0); Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], } } /// Iterates over all static translation table entries and fills them at once. /// /// # Safety /// /// - Modifies a `static mut`. Ensure it only happens from here. pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { *l2_entry = TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); let (phys_output_addr, attribute_fields) = bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); } } Ok(()) } /// The translation table's base address to be used for programming the MMU. pub fn phys_base_address(&self) -> u64 { self.lvl2.phys_start_addr_u64() } } ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::arch_mmu use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Memory Management Unit type. struct MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; /// Constants for indexing the MAIR_EL1. #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. /// /// # Safety /// /// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); static MMU: MemoryManagementUnit = MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AddressSpace { /// Checks for architectural restrictions. pub const fn arch_address_space_size_sanity_checks() { // Size must be at least one full 512 MiB table. assert!((AS_SIZE % Granule512MiB::SIZE) == 0); // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 // version. assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } /// Configure various settings of stage 1 of the EL1 translation regime. fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the MMU instance. pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use memory::mmu::MMUEnableError; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } // Fail early if translation granule is not supported. if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } // Prepare the memory attribute indirection register. self.set_up_mair(); // Populate translation tables. KERNEL_TABLES .populate_tt_entries() .map_err(MMUEnableError::Other)?; // Set the "Translation Table Base Register". TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); self.configure_translation_control(); // Switch the MMU on. // // First, force all previous changes to be seen before the MMU is enabled. barrier::isb(barrier::SY); // Enable the MMU and turn on data and instruction caching. SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); // Force MMU init to complete before next instruction. barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } } ================================================ FILE: 11_exceptions_part1_groundwork/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/raspberrypi/driver.rs ================================================ // 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(()) } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW * * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. * It doesn't mean all of them need actually be loaded. */ PHDRS { segment_boot_core_stack PT_LOAD FLAGS(6); segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); } SECTIONS { . = __rpi_phys_dram_start_addr; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : { /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __code_start = .; .text : { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ *(.text._start_rust) /* The Rust entry point */ *(.text*) /* Everything else */ } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { __bss_start = .; *(.bss*); . = ALIGN(16); __bss_end_exclusive = .; } :segment_data /*********************************************************************************************** * Misc ***********************************************************************************************/ .got : { *(.got*) } ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") /DISCARD/ : { *(.comment*) } } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. use super::map as memory_map; use crate::memory::mmu::*; use core::ops::RangeInclusive; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The kernel's address space defined by this BSP. pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; const NUM_MEM_RANGES: usize = 2; /// The virtual memory layout. /// /// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. /// It is agnostic of the paging granularity that the architecture's MMU will use. pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( memory_map::END_INCLUSIVE, [ TranslationDescriptor { name: "Kernel code and RO data", virtual_range: code_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadOnly, execute_never: false, }, }, TranslationDescriptor { name: "Device MMIO", virtual_range: mmio_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, }, ], ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- fn code_range_inclusive() -> RangeInclusive { // Notice the subtraction to turn the exclusive end into an inclusive end. #[allow(clippy::range_minus_one)] RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) } fn mmio_range_inclusive() -> RangeInclusive { RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the virtual memory layout. pub fn virt_mem_layout() -> &'static KernelVirtualLayout { &LAYOUT } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! //! The physical memory layout. //! //! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used //! as the boot core's stack. //! //! +---------------------------------------+ //! | | 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | //! | | pub mod mmu; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // Symbols from the linker script. extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { /// The inclusive end address of the memory map. /// /// End address + 1 must be power of two. /// /// # Note /// /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. /// /// However, making this trade-off has the downside of making it possible for the CPU to assert a /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const END_INCLUSIVE: usize = 0x4000_FFFF; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const END_INCLUSIVE: usize = 0xFF84_FFFF; } } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Start page address of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_start() -> usize { unsafe { __code_start.get() as usize } } /// Exclusive end page address of the code segment. /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_end_exclusive() -> usize { unsafe { __code_end_exclusive.get() as usize } } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 11_exceptions_part1_groundwork/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 11_exceptions_part1_groundwork/src/common.rs ================================================ // 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") } } ================================================ FILE: 11_exceptions_part1_groundwork/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 11_exceptions_part1_groundwork/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 11_exceptions_part1_groundwork/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 11_exceptions_part1_groundwork/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; ================================================ FILE: 11_exceptions_part1_groundwork/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 11_exceptions_part1_groundwork/src/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/exception/asynchronous.rs"] mod arch_asynchronous; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_asynchronous::print_state; ================================================ FILE: 11_exceptions_part1_groundwork/src/exception.rs ================================================ // 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, } ================================================ FILE: 11_exceptions_part1_groundwork/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![allow(incomplete_features)] #![feature(asm_const)] #![feature(const_option)] #![feature(core_intrinsics)] #![feature(format_args_nl)] #![feature(int_roundings)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_main] #![no_std] mod bsp; mod common; mod console; mod cpu; mod driver; mod exception; mod memory; mod panic_wait; mod print; mod synchronization; mod time; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order: /// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, /// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ /// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { panic!("MMU: {}", string); } // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { use console::console; use core::time::Duration; info!( "{} version {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION") ); info!("Booting on: {}", bsp::board_name()); info!("MMU online. Special regions:"); bsp::memory::mmu::virt_mem_layout().print_layout(); let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); info!("Exception handling state:"); exception::asynchronous::print_state(); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); info!("Timer test, spinning for 1 second"); time::time_manager().spin_for(Duration::from_secs(1)); // Cause an exception by accessing a virtual address for which no translation was set up. This // code accesses the address 8 GiB, which is outside the mapped address space. // // For demo purposes, the exception handler will catch the faulting 8 GiB address and allow // execution to continue. info!(""); info!("Trying to read from address 8 GiB..."); let mut big_addr: u64 = 8 * 1024 * 1024 * 1024; unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; info!("************************************************"); info!("Whoa! We recovered from a synchronous exception!"); info!("************************************************"); info!(""); info!("Let's try again"); // Now use address 9 GiB. The exception handler won't forgive us this time. info!("Trying to read from address 9 GiB..."); big_addr = 9 * 1024 * 1024 * 1024; unsafe { core::ptr::read_volatile(big_addr as *mut u64) }; // Will never reach here in this tutorial. info!("Echoing input now"); // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { let c = console().read_char(); console().write_char(c); } } ================================================ FILE: 11_exceptions_part1_groundwork/src/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Translation table. #[cfg(target_arch = "aarch64")] #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] mod arch_translation_table; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_translation_table::KernelTranslationTable; ================================================ FILE: 11_exceptions_part1_groundwork/src/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! //! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file //! provides types for composing an architecture-agnostic description of the kernel's virtual memory //! layout. //! //! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` //! function. //! //! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and //! install respective translation tables. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; mod translation_table; use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_mmu::mmu; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// MMU enable errors variants. #[allow(missing_docs)] #[derive(Debug)] pub enum MMUEnableError { AlreadyEnabled, Other(&'static str), } /// Memory Management interfaces. pub mod interface { use super::*; /// MMU functions. pub trait MMU { /// Called by the kernel during early init. Supposed to take the translation tables from the /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. /// /// # Safety /// /// - Changes the HW's global state. unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; } } /// Describes the characteristics of a translation granule. pub struct TranslationGranule; /// Describes properties of an address space. pub struct AddressSpace; /// Architecture agnostic translation types. #[allow(missing_docs)] #[allow(dead_code)] #[derive(Copy, Clone)] pub enum Translation { Identity, Offset(usize), } /// Architecture agnostic memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum MemAttributes { CacheableDRAM, Device, } /// Architecture agnostic access permissions. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum AccessPermissions { ReadOnly, ReadWrite, } /// Collection of memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, pub execute_never: bool, } /// Architecture agnostic descriptor for a memory range. #[allow(missing_docs)] pub struct TranslationDescriptor { pub name: &'static str, pub virtual_range: fn() -> RangeInclusive, pub physical_range_translation: Translation, pub attribute_fields: AttributeFields, } /// Type for expressing the kernel's virtual memory layout. pub struct KernelVirtualLayout { /// The last (inclusive) address of the address space. max_virt_addr_inclusive: usize, /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl fmt::Display for MMUEnableError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), MMUEnableError::Other(x) => write!(f, "{}", x), } } } impl TranslationGranule { /// The granule's size. pub const SIZE: usize = Self::size_checked(); /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(GRANULE_SIZE.is_power_of_two()); GRANULE_SIZE } } impl AddressSpace { /// The address space size. pub const SIZE: usize = Self::size_checked(); /// The address space shift, aka log2(size). pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(AS_SIZE.is_power_of_two()); // Check for architectural restrictions as well. Self::arch_address_space_size_sanity_checks(); AS_SIZE } } impl Default for AttributeFields { fn default() -> AttributeFields { AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, } } } /// Human-readable output of a TranslationDescriptor. impl fmt::Display for TranslationDescriptor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Call the function to which self.range points, and dereference the result, which causes // Rust to copy the value. let start = *(self.virtual_range)().start(); let end = *(self.virtual_range)().end(); let size = end - start + 1; let (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", MemAttributes::Device => "Dev", }; let acc_p = match self.attribute_fields.acc_perms { AccessPermissions::ReadOnly => "RO", AccessPermissions::ReadWrite => "RW", }; let xn = if self.attribute_fields.execute_never { "PXN" } else { "PX" }; write!( f, " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", start, end, size, unit, attr, acc_p, xn, self.name ) } } impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { /// Create a new instance. pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { Self { max_virt_addr_inclusive: max, inner: layout, } } /// For a virtual address, find and return the physical output address and corresponding /// attributes. /// /// If the address is not found in `inner`, return an identity mapped default with normal /// cacheable DRAM attributes. pub fn virt_addr_properties( &self, virt_addr: usize, ) -> Result<(usize, AttributeFields), &'static str> { if virt_addr > self.max_virt_addr_inclusive { return Err("Address out of range"); } for i in self.inner.iter() { if (i.virtual_range)().contains(&virt_addr) { let output_addr = match i.physical_range_translation { Translation::Identity => virt_addr, Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), }; return Ok((output_addr, i.attribute_fields)); } } Ok((virt_addr, AttributeFields::default())) } /// Print the memory layout. pub fn print_layout(&self) { use crate::info; for i in self.inner.iter() { info!("{}", i); } } } ================================================ FILE: 11_exceptions_part1_groundwork/src/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management. pub mod mmu; ================================================ FILE: 11_exceptions_part1_groundwork/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", timestamp.as_secs(), timestamp.subsec_micros(), location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: 11_exceptions_part1_groundwork/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 11_exceptions_part1_groundwork/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 11_exceptions_part1_groundwork/src/time.rs ================================================ // 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) } } ================================================ FILE: 11_exceptions_part1_groundwork/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'lr : 0x' ================================================ FILE: 12_integrated_testing/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 12_integrated_testing/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 12_integrated_testing/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel" ] [profile.release] lto = true ================================================ FILE: 12_integrated_testing/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 # Optional integration test name. ifdef TEST TEST_ARG = --test $(TEST) else TEST_ARG = --test '*' endif ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = kernel/Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot test_unit test_integration test_unit test_integration: FEATURES += --features test_build ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test_unit test_integration test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER #!/usr/bin/env bash # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure # this script executes from the root. cd $(shell pwd) TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY endef export KERNEL_TEST_RUNNER define test_prepare @mkdir -p target @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh @chmod +x target/kernel_test_runner.sh endef ##------------------------------------------------------------------------------ ## Run unit test(s) ##------------------------------------------------------------------------------ test_unit: $(call color_header, "Compiling unit test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib ##------------------------------------------------------------------------------ ## Run integration test(s) ##------------------------------------------------------------------------------ test_integration: $(call color_header, "Compiling integration test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) test: test_boot test_unit test_integration endif ================================================ FILE: 12_integrated_testing/README.md ================================================ # Tutorial 12 - Integrated Testing ## tl;dr - We implement our own integrated test framework using `Rust`'s [custom_test_frameworks] feature by enabling `Unit Tests` and `Integration Tests` using `QEMU`. - It is also possible to have test automation for I/O with the kernel's `console` (provided over `UART` in our case). That is, sending strings/characters to the console and expecting specific answers in return. - The already existing basic `boot test` remains unchanged. ## Table of Contents - [Introduction](#introduction) - [Challenges](#challenges) * [Acknowledgements](#acknowledgements) - [Folder Restructuring](#folder-restructuring) - [Implementation](#implementation) * [Test Organization](#test-organization) * [Enabling `custom_test_frameworks` for Unit Tests](#enabling-custom_test_frameworks-for-unit-tests) + [The Unit Test Runner](#the-unit-test-runner) + [Calling the Test `main()` Function](#calling-the-test-main-function) * [Quitting QEMU with user-defined Exit Codes](#quitting-qemu-with-user-defined-exit-codes) + [Exiting Unit Tests](#exiting-unit-tests) * [Controlling Test Kernel Execution](#controlling-test-kernel-execution) + [Wrapping QEMU Test Execution](#wrapping-qemu-test-execution) * [Writing Unit Tests](#writing-unit-tests) * [Integration Tests](#integration-tests) + [Test Harness](#test-harness) + [No Test Harness](#no-test-harness) + [Overriding Panic Behavior](#overriding-panic-behavior) * [Console Tests](#console-tests) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction Through the course of the previous tutorials, we silently started to adopt a kind of anti-pattern: Using the kernel's main function to not only boot the target, but also test or showcase functionality. For example: - Stalling execution during boot to test the kernel's timekeeping code by spinning for 1 second. - Willingly causing exceptions to see the exception handler running. The feature set of the kernel is now rich enough so that it makes sense to introduce proper integrated testing modeled after Rust's [native testing framework]. This tutorial extends our single existing kernel test with three new testing facilities: - Classic `Unit Tests`. - [Integration Tests] (self-contained tests stored in the `$CRATE/tests/` directory). - `Console I/O Tests`. These are integration tests acting on external stimuli - aka `console` input. Sending strings/characters to the console and expecting specific answers in return. [native testing framework]: https://doc.rust-lang.org/book/ch11-00-testing.html ## Challenges Testing Rust `#![no_std]` code like our kernel is, at the point of writing this tutorial, not an easy endeavor. The short version is: We cannot use Rust's [native testing framework] straight away. Utilizing the `#[test]` attribute macro and running `cargo test` would throw compilation errors, because there are dependencies on the standard library. [native testing framework]: https://doc.rust-lang.org/book/ch11-00-testing.html We have to fall back to Rust's unstable [custom_test_frameworks] feature. It relieves us from dependencies on the standard library, but comes at the cost of having a reduced feature set. Instead of annotating functions with `#[test]`, the `#[test_case]` attribute must be used. Additionally, we need to write a `test_runner` function, which is supposed to execute all the functions annotated with `#[test_case]`. This is barely enough to get `Unit Tests` running, though. There will be some more challenges that need be solved for getting `Integration Tests` running as well. Please note that for automation purposes, all testing will be done in `QEMU` and not on real hardware. [custom_test_frameworks]: https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html [Integration Tests]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests ### Acknowledgements On this occasion, kudos to [@phil-opp] for his x86-based [testing] article. It helped a lot in putting together this tutorial. Please go ahead and read it for a different perspective and additional insights. [testing]: https://os.phil-opp.com/testing ## Folder Restructuring For reasons explained later, in this tutorial, we need to add two support crates next to our main kernel crate. To keep everything organized in separate directories, we are switching to what `cargo` calls a [virtual manifest]. The kernel crate moves to `$ROOT/kernel`, and the support crates will go into `$ROOT/libraries/`. The `Cargo.toml` in the `$ROOT` folder desribes this layout: ```toml [workspace] members = [ "libraries/*", "kernel" ] ``` [virtual manifest]: https://doc.rust-lang.org/cargo/reference/workspaces.html#virtual-manifest ## Implementation We introduce two new `Makefile` targets: ```console $ make test_unit $ make test_integration ``` In essence, the `make test_*` targets will execute `cargo test` instead of `cargo rustc`. The details will be explained in due course. The rest of the tutorial will explain as chronologically as possible what happens when `make test_*` aka `cargo test` runs. Please note that the new targets are added to the existing `make test` target, so this is now your one-stop target to execute all possible tests for the kernel: ```Makefile test: test_boot test_unit test_integration ``` ### Test Organization Until now, our kernel crate was a so-called `binary crate`. As [explained in the official Rust book], this crate type disallows having `integration tests`. Quoting the book: [explained in the official Rust book]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests-for-binary-crates > If our project is a binary crate that only contains a _src/main.rs_ file and doesn’t have a > _src/lib.rs_ file, we can’t create integration tests in the _tests_ directory and bring functions > defined in the _src/main.rs_ file into scope with a `use` statement. Only library crates expose > functions that other crates can use; binary crates are meant to be run on their own. > This is one of the reasons Rust projects that provide a binary have a straightforward > _src/main.rs_ file that calls logic that lives in the _src/lib.rs_ file. Using that structure, > integration tests _can_ test the library crate with `use` to make the important functionality > available. If the important functionality works, the small amount of code in the _src/main.rs_ > file will work as well, and that small amount of code doesn’t need to be tested. So let's do that first: We add a `lib.rs` to our crate that aggregates and exports the lion's share of the kernel code. The `main.rs` file is stripped down to the minimum. It only keeps the `kernel_init() -> !` and `kernel_main() -> !` functions, everything else is brought into scope with `use` statements. Since it is not possible to use `kernel` as the name for both the library and the binary part of the crate, new entries in `$ROOT/kernel/Cargo.toml` are needed to differentiate the names. What's more, `cargo test` would try to compile and run `unit tests` for both. In our case, it will be sufficient to have all the unit test code in `lib.rs`, so test generation for `main.rs` can be disabled in `Cargo.toml` as well through the `test` flag: ```toml [lib] name = "libkernel" test = true [[bin]] name = "kernel" test = false ``` ### Enabling `custom_test_frameworks` for Unit Tests In `lib.rs`, we add the following headers to get started with `custom_test_frameworks`: ```rust // Testing #![cfg_attr(test, no_main)] #![feature(custom_test_frameworks)] #![reexport_test_harness_main = "test_main"] #![test_runner(crate::test_runner)] ``` Since this is a library now, we do not keep the `#![no_main]` inner attribute that `main.rs` has, because a library has no `main()` entry function, so the attribute does not apply. When compiling for testing, though, it is still needed. The reason is that `cargo test` basically turns `lib.rs` into a binary again by inserting a generated `main()` function (which is then calling a function that runs all the unit tests, but more about that in a second...). However, since our kernel code [overrides the compiler-inserted `main` shim] by way of using `#![no_main]`, we need the same when `cargo test` is producing its test kernel binary. After all, what we want is a minimal kernel that boots on the target and runs its own unit tests. Therefore, we conditionally set this attribute (`#![cfg_attr(test, no_main)]`) when the `test` flag is set, which it is when `cargo test` runs. [overrides the compiler-inserted `main` shim]: https://doc.rust-lang.org/unstable-book/language-features/lang-items.html?highlight=no_main#writing-an-executable-without-stdlib #### The Unit Test Runner The `#![test_runner(crate::test_runner)]` attribute declares the path of the test runner function that we are supposed to provide. This is the one that will be called by the `cargo test` generated `main()` function. Here is the implementation in `lib.rs`: ```rust /// The default runner for unit tests. pub fn test_runner(tests: &[&test_types::UnitTest]) { // This line will be printed as the test header. println!("Running {} tests", tests.len()); for (i, test) in tests.iter().enumerate() { print!("{:>3}. {:.<58}", i + 1, test.name); // Run the actual test. (test.test_func)(); // Failed tests call panic!(). Execution reaches here only if the test has passed. println!("[ok]") } } ``` The function signature shows that `test_runner` takes one argument: A slice of `test_types::UnitTest` references. This type definition lives in an external crate stored at `$ROOT/libraries/test_types`. It is external because the type is also needed for a self-made [procedural macro] that we'll use to write unit tests, and procedural macros _have_ to live in their own crate. So to avoid a circular dependency between kernel and proc-macro, this split was needed. Anyways, here is the type definition: [procedural macro]: https://doc.rust-lang.org/reference/procedural-macros.html ```rust /// Unit test container. pub struct UnitTest { /// Name of the test. pub name: &'static str, /// Function pointer to the test. pub test_func: fn(), } ``` A `UnitTest` provides a name and a classic function pointer to the unit test function. The `test_runner` just iterates over the slice, prints the respective test's name and calls the test function. The convetion is that as long as the test function does not `panic!`, the test was successful. #### Calling the Test `main()` Function The last of the attributes we added is `#![reexport_test_harness_main = "test_main"]`. Remember that our kernel uses the `no_main` attribute, and that we also set it for the test compilation. We did that because we wrote our own `_start()` function, which kicks off the following call chain during kernel boot: | | Function | File | | - | - | - | | 1. | `_start()` | The library's `boot.s` | | 2. | (some more aarch64 code) | The library's `boot.rs` | | 3. | `kernel_init()` | `main.rs` | | 4. | `kernel_main()` | `main.rs` | A function named `main` is never called. Hence, the `main()` function generated by `cargo test` would be silently dropped, and therefore the tests would never be executed. As you can see, the first function getting called in our carved-out `main.rs` is `kernel_init()`. So in order to get the tests to execute, we add a test-environment version of `kernel_init()` to `lib.rs` as well (conditional compilation ensures it is only present when the test flag is set), and call the `cargo test` generated `main()` function from there. This is where `#![reexport_test_harness_main = "test_main"]` finally comes into picture. It declares the name of the generated main function so that we can manually call it. Here is the final implementation in `lib.rs`: ```rust /// The `kernel_init()` for unit tests. #[cfg(test)] #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); bsp::driver::qemu_bring_up_console(); test_main(); cpu::qemu_exit_success() } ``` Note the call to `bsp::driver::qemu_bring_up_console()`. Since we are running all our tests inside `QEMU`, we need to ensure that whatever peripheral implements the kernel's `console` interface is initialized, so that we can print from our tests. If you recall [tutorial 03], bringing up peripherals in `QEMU` might not need the full initialization as is needed on real hardware (setting clocks, config registers, etc...) due to the abstractions in `QEMU`'s emulation code. So this is an opportunity to cut down on setup code. [tutorial 03]: ../03_hacky_hello_world As a matter of fact, for the `Raspberrys`, nothing needs to be done, so the function is empy. But this might be different for other hardware emulated by `QEMU`, so it makes sense to introduce the function now to make it easier in case new `BSPs` are added to the kernel in the future. Next, the reexported `test_main()` is called, which will call our `test_runner()` which finally prints the unit test names and executes them. ### Quitting QEMU with user-defined Exit Codes Let's recap where we are right now: We've enabled `custom_test_frameworks` in `lib.rs` to a point where, when using a `make test_unit` target, the code gets compiled to a test kernel binary that eventually executes all the (yet-to-be-defined) `UnitTest` instances by executing all the way from `_start()` to our `test_runner()` function. Through mechanisms that are explained later, `cargo` will now instantiate a `QEMU` process that exectues this test kernel. The question now is: How is test success/failure communicated to `cargo`? Answer: `cargo` inspects `QEMU`'s [exit status]: - `0` translates to testing was successful. - `non-0` means failure. Hence, we need a clever trick now so that our Rust kernel code can get `QEMU` to exit itself with an exit status that the kernel code supplies. In [@phil-opp]'s testing article, you [learned how to do this] for `x86 QEMU` systems by using a special `ISA` debug-exit device. Unfortunately, we can't have that one for our `aarch64` system because it is not compatible. In our case, we can leverage the ARM [semihosting] emulation of `QEMU` and do a `SYS_EXIT` semihosting call with an additional parameter for the exit code. I've written a separate crate, [qemu-exit], to do this. So let us import it and utilize it in `_arch/aarch64/cpu.rs` to provide the following exit calls for the kernel: ```rust //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(feature = "test_build")] use qemu_exit::QEMUExit; #[cfg(feature = "test_build")] const QEMU_EXIT_HANDLE: qemu_exit::AArch64 = qemu_exit::AArch64::new(); /// Make the host QEMU binary execute `exit(1)`. #[cfg(feature = "test_build")] pub fn qemu_exit_failure() -> ! { QEMU_EXIT_HANDLE.exit_failure() } /// Make the host QEMU binary execute `exit(0)`. #[cfg(feature = "test_build")] pub fn qemu_exit_success() -> ! { QEMU_EXIT_HANDLE.exit_success() } ``` [Click here] in case you are interested in the implementation. Note that for the functions to work, the `-semihosting` flag must be added to the `QEMU` invocation. You might have also noted the `#[cfg(feature = "test_build")]`. In the `Makefile`, we ensure that this feature is only enabled when `cargo test` runs. This way, it is ensured that testing-specific code is conditionally compiled only for testing. [exit status]: https://en.wikipedia.org/wiki/Exit_status [@phil-opp]: https://github.com/phil-opp [learned how to do this]: https://os.phil-opp.com/testing/#exiting-qemu [semihosting]: https://static.docs.arm.com/100863/0200/semihosting.pdf [qemu-exit]: https://github.com/andre-richter/qemu-exit [Click here]: https://github.com/andre-richter/qemu-exit/blob/master/src/aarch64.rs #### Exiting Unit Tests Unit test failure shall be triggered by the `panic!` macro, either directly or by way of using `assert!` macros. Until now, our `panic!` implementation finally called `cpu::wait_forever()` to safely park the panicked CPU core in a busy loop. This can't be used for the unit tests, because `cargo` would wait forever for `QEMU` to exit and stall the whole test run. Again, conditional compilation is used to differentiate between a release and testing version of how a `panic!` concludes: ```rust /// The point of exit for `libkernel`. /// /// It is linked weakly, so that the integration tests can overload its standard behavior. #[linkage = "weak"] #[no_mangle] fn _panic_exit() -> ! { #[cfg(not(feature = "test_build"))] { cpu::wait_forever() } #[cfg(feature = "test_build")] { cpu::qemu_exit_failure() } } ``` In case _none_ of the unit tests panicked, `lib.rs`'s `kernel_init()` calls `cpu::qemu_exit_success()` to successfully conclude the unit test run. ### Controlling Test Kernel Execution Now is a good time to catch up on how the test kernel binary is actually being executed. Normally, `cargo test` would try to execute the compiled binary as a normal child process. This would fail horribly because we build a kernel, and not a userspace process. Also, chances are high that you sit in front of an `x86` machine, whereas the RPi kernel is `AArch64`. Therefore, we need to install some hooks that make sure the test kernel gets executed inside `QEMU`, quite like it is done for the existing `make qemu` target that is in place since `tutorial 1`. The first step is to add a new file to the project, `.cargo/config.toml`: ```toml [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ``` Instead of executing a compilation result directly, the `runner` flag will instruct `cargo` to delegate the execution. Using the setting depicted above, `target/kernel_test_runner.sh` will be executed and given the full path to the compiled test kernel as the first command line argument. The file `kernel_test_runner.sh` does not exist by default. We generate it on demand when one of the `make test_*` targets is called: ```Makefile ##------------------------------------------------------------------------------ ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER #!/usr/bin/env bash # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure # this script executes from the root. cd $(shell pwd) TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY endef export KERNEL_TEST_RUNNER define test_prepare @mkdir -p target @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh @chmod +x target/kernel_test_runner.sh endef ##------------------------------------------------------------------------------ ## Run unit test(s) ##------------------------------------------------------------------------------ test_unit: $(call color_header, "Compiling unit test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib ``` It first does the standard `objcopy` step to strip the `ELF` down to a raw binary. Just like in all the other Makefile targets. Next, the script generates a relative path from the absolute path provided to it by `cargo`, and finally compiles a `docker` command to execute the test kernel. For reference, here it is fully resolved for an `RPi3 BSP`: ```bash docker run -t --rm -v /opt/rust-raspberrypi-OS-tutorials/12_integrated_testing:/work/tutorial -w /work/tutorial -v /opt/rust-raspberrypi-OS-tutorials/12_integrated_testing/../common:/work/common rustembedded/osdev-utils:2021.12 ruby ../common/tests/dispatch.rb qemu-system-aarch64 -M raspi3 -serial stdio -display none -semihosting -kernel $TEST_BINARY ``` This command is quite similar to the one used in the `make test_boot` target that we have since `tutorial 3`. However, we never bothered explaining it, so lets take a closer look this time. One of the key ingredients is that we execute this script: `ruby ../common/tests/dispatch.rb`. #### Wrapping QEMU Test Execution `dispatch.rb` is a [Ruby] script which first determines what kind of test is due by inspecting the `QEMU`-command that was given to it. In case of `unit tests`, we are only interested if they all executed successfully, which can be checked by inspecting `QEMU`'s exit code. So the script takes the provided qemu command it got from `ARGV`, and creates and runs an instance of `ExitCodeTest`: ```ruby qemu_cmd = ARGV.join(' ') binary = ARGV.last test_name = binary.gsub(%r{.*deps/}, '').split('-')[0] # Check if virtual manifest (tutorial 12 or later) or not path_prefix = File.exist?('kernel/Cargo.toml') ? 'kernel/' : '' case test_name when 'kernel8.img' load "#{path_prefix}tests/boot_test_string.rb" # provides 'EXPECTED_PRINT' BootTest.new(qemu_cmd, EXPECTED_PRINT).run # Doesn't return when 'libkernel' ExitCodeTest.new(qemu_cmd, 'Kernel library unit tests').run # Doesn't return ``` The easy case is `QEMU` exiting by itself by means of `aarch64::exit_success()` or `aarch64::exit_failure()`. But the script can also catch the case of a test that gets stuck, e.g. in an unintentional busy loop or a crash. If `ExitCodeTest` does not observe any output of the test kernel for `MAX_WAIT_SECS`, it cancels the execution and marks the test as failed. Test success or failure is finally reported back to `cargo`. Here is the essential part happening in `class ExitCodeTest` (If `QEMU` exits itself, an `EOFError` is thrown): ```ruby def run_concrete_test Timeout.timeout(MAX_WAIT_SECS) do @test_output << @qemu_serial.read_nonblock(1024) while @qemu_serial.wait_readable end rescue EOFError @qemu_serial.close @test_error = $CHILD_STATUS.to_i.zero? ? false : 'QEMU exit status != 0' rescue Timeout::Error @test_error = 'Timed out waiting for test' rescue StandardError => e @test_error = e.inspect end ``` Please note that `dispatch.rb` and all its dependencies live in the shared folder `../common/tests/`. [Ruby]: https://www.ruby-lang.org/ ### Writing Unit Tests Alright, that's a wrap for the whole chain from `make test_unit` all the way to reporting the test exit status back to `cargo test`. It is a lot to digest already, but we haven't even learned to write `Unit Tests` yet. In essence, it is almost like in `std` environments, with the difference that `#[test]` can't be used, because it is part of the standard library. The `no_std` replacement attribute provided by `custom_test_frameworks` is `#[test_case]`. You can put `#[test_case]` before functions, constants or statics (you have to decide for one and stick with it). Each attributed item is added to the "list" that is then passed to the `test_runner` function. As you learned earlier, we decided that our tests shall be instances of `test_types::UnitTest`. Here is the type definition again: ```rust /// Unit test container. pub struct UnitTest { /// Name of the test. pub name: &'static str, /// Function pointer to the test. pub test_func: fn(), } ``` So what we could do now is write something like: ```rust #[cfg(test)] mod tests { use super::*; #[test_case] const TEST1: test_types::UnitTest = test_types::UnitTest { name: "test_runner_executes_in_kernel_mode", test_func: || { let (level, _) = current_privilege_level(); assert!(level == PrivilegeLevel::Kernel) }, }; } ``` Since this is a bit boiler-platy with the const and name definition, let's write a [procedural macro] named `#[kernel_test]` to simplify this. It should work this way: 1. Must be put before functions that take no arguments and return nothing. 1. Automatically constructs a `const UnitTest` from attributed functions like shown above by: 1. Converting the function name to the `name` member of the `UnitTest` struct. 1. Populating the `test_func` member with a closure that executes the body of the attributed function. For the sake of brevity, we're not going to discuss the macro implementation. [The source is in the test-macros crate] if you're interested in it. Using the macro, the example shown before now boils down to this (this is now an actual example from [exception.rs]: [procedural macro]: https://doc.rust-lang.org/reference/procedural-macros.html [The source is in the test-macros crate]: test-macros/src/lib.rs [exception.rs]: src/exception.rs ```rust #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Libkernel unit tests must execute in kernel mode. #[kernel_test] fn test_runner_executes_in_kernel_mode() { let (level, _) = current_privilege_level(); assert!(level == PrivilegeLevel::Kernel) } } ``` Note that since proc macros need to live in their own crates, we need to create a new one at `$ROOT/libraries/test-macros` and save it there. Aaaaaand that's how you write unit tests. We're finished with that part for good now :raised_hands:. ### Integration Tests We are still not done with the tutorial, though :scream:. Integration tests need some special attention here and there too. As you already learned, they live in `$CRATE/tests/`. Each `.rs` file in there gets compiled into its own test kernel binary and executed separately by `cargo test`. The code in the integration tests includes the library part of our kernel (`libkernel`) through `use` statements. Also note that the entry point for each `integration test` must be the `kernel_init()` function again, just like in the `unit test` case. #### Test Harness By default, `cargo test` will pull in the test harness (that's the official name for the generated `main()` function) into integration tests as well. This gives you a further means of partitioning your test code into individual chunks. For example, take a look at `tests/01_timer_sanity.rs`: ```rust //! Timer sanity tests. #![feature(custom_test_frameworks)] #![no_main] #![no_std] #![reexport_test_harness_main = "test_main"] #![test_runner(libkernel::test_runner)] use core::time::Duration; use libkernel::{bsp, cpu, exception, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. test_main(); cpu::qemu_exit_success() } /// Simple check that the timer is running. #[kernel_test] fn timer_is_counting() { assert!(time::time_manager().uptime().as_nanos() > 0) } /// Timer resolution must be sufficient. #[kernel_test] fn timer_resolution_is_sufficient() { assert!(time::time_manager().resolution().as_nanos() > 0); assert!(time::time_manager().resolution().as_nanos() < 100) } ``` Note how the `test_runner` from `libkernel` is pulled in through `#![test_runner(libkernel::test_runner)]`. #### No Test Harness For some tests, however, it is not needed to have the harness, because there is no need or possibility to partition the test into individual pieces. In this case, all the test code can live in `kernel_init()`, and harness generation can be turned off through `$ROOT/kernel/Cargo.toml`. This tutorial introduces two tests that don't need a harness. Here is how harness generation is turned off for them: ```toml # List of tests without harness. [[test]] name = "00_console_sanity" harness = false [[test]] name = "02_exception_sync_page_fault" harness = false [[test]] name = "03_exception_restore_sanity" harness = false ``` #### Overriding Panic Behavior Did you notice the `#[linkage = "weak"]` attribute some chapters earlier at the `_panic_exit()` function? This marks the function in `lib.rs` as a [weak symbol]. Let's look at it again: ```rust /// The point of exit for `libkernel`. /// /// It is linked weakly, so that the integration tests can overload its standard behavior. #[linkage = "weak"] #[no_mangle] fn _panic_exit() -> ! { #[cfg(not(feature = "test_build"))] { cpu::wait_forever() } #[cfg(feature = "test_build")] { cpu::qemu_exit_failure() } } ``` [weak symbol]: https://en.wikipedia.org/wiki/Weak_symbol This enables integration tests in `$CRATE/tests/` to override this function according to their needs. This is useful, because depending on the kind of test, a `panic!` could mean success or failure. For example, `tests/02_exception_sync_page_fault.rs` is intentionally causing a page fault, so the wanted outcome is a `panic!`. Here is the whole test (minus some inline comments): ```rust //! Page faults must result in synchronous exceptions. #![feature(format_args_nl)] #![no_main] #![no_std] mod panic_exit_success; use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { info!("MMU: {}", string); cpu::qemu_exit_failure() } info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); // If execution reaches here, the memory access above did not cause a page fault exception. cpu::qemu_exit_failure() } ``` The `_panic_exit()` version that makes `QEMU` return `0` (indicating test success) is pulled in by `mod panic_exit_success;`, and it will take precedence over the `weak` version from `lib.rs`. ### Console Tests As the kernel or OS grows, it will be more and more interesting to test user/kernel interaction through the serial console. That is, sending strings/characters to the console and expecting specific answers in return. The `dispatch.rb` wrapper script provides infrastructure to recognize and dispatch console I/O tests with little overhead. It basically works like this: 1. For each integration test, check if a companion file to the `.rs` test file exists. - A companion file has the same name, but ends in `.rb`. - The companion file contains one or more console I/O subtests. 1. If it exists, load the file to dynamically import the console subtests. 1. Create a `ConsoleIOTest` instance and run it. - This first spawns `QEMU` and attaches to `QEMU`'s serial console emulation. - Then it runs all console subtests on it. Here is an excerpt from `00_console_sanity.rb` showing a subtest that does a handshake with the kernel over the console: ```ruby require 'console_io_test' # Verify sending and receiving works as expected. class TxRxHandshakeTest < SubtestBase def name 'Transmit and Receive handshake' end def run(qemu_out, qemu_in) qemu_in.write_nonblock('ABC') expect_or_raise(qemu_out, 'OK1234') end end ``` The subtest first sends `"ABC"` over the console to the kernel, and then expects to receive `"OK1234"` back. On the kernel side, it looks like this in `00_console_sanity.rs`: ```rust #![feature(format_args_nl)] #![no_main] #![no_std] /// Console tests should time out on the I/O harness in case of panic. mod panic_wait_forever; use libkernel::{bsp, console, cpu, exception, print}; #[no_mangle] unsafe fn kernel_init() -> ! { use console::console; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); assert_eq!(console().read_char(), 'B'); assert_eq!(console().read_char(), 'C'); print!("OK1234"); ``` ## Test it Believe it or not, that is all. There are four ways you can run tests now: 1. `make test` will run all tests back-to-back. That is, the ever existing `boot test` first, then `unit tests`, then `integration tests`. 1. `make test_unit` will run `libkernel`'s unit tests. 1. `make test_integration` will run all integration tests back-to-back. 1. `TEST=TEST_NAME make test_integration` will run a specficic integration test. - For example, `TEST=01_timer_sanity make test_integration` ```console $ make test [...] Running unittests (target/aarch64-unknown-none-softfloat/release/deps/libkernel-142a8d94bc9c615a) ------------------------------------------------------------------- 🦀 Running 6 tests ------------------------------------------------------------------- 1. virt_mem_layout_sections_are_64KiB_aligned................[ok] 2. virt_mem_layout_has_no_overlaps...........................[ok] 3. test_runner_executes_in_kernel_mode.......................[ok] 4. kernel_tables_in_bss......................................[ok] 5. size_of_tabledescriptor_equals_64_bit.....................[ok] 6. size_of_pagedescriptor_equals_64_bit......................[ok] ------------------------------------------------------------------- ✅ Success: Kernel library unit tests ------------------------------------------------------------------- Compiling integration test(s) - rpi3 Finished release [optimized] target(s) in 0.00s Running tests/00_console_sanity.rs (target/aarch64-unknown-none-softfloat/release/deps/00_console_sanity-c06130838f14dbff) ------------------------------------------------------------------- 🦀 Running 3 console I/O tests ------------------------------------------------------------------- 1. Transmit and Receive handshake............................[ok] 2. Transmit statistics.......................................[ok] 3. Receive statistics........................................[ok] Console log: ABCOK123463 ------------------------------------------------------------------- ✅ Success: 00_console_sanity.rs ------------------------------------------------------------------- Running tests/01_timer_sanity.rs (target/aarch64-unknown-none-softfloat/release/deps/01_timer_sanity-62a954d22239d1a3) ------------------------------------------------------------------- 🦀 Running 3 tests ------------------------------------------------------------------- 1. timer_is_counting.........................................[ok] 2. timer_resolution_is_sufficient............................[ok] 3. spin_accuracy_check_1_second..............................[ok] ------------------------------------------------------------------- ✅ Success: 01_timer_sanity.rs ------------------------------------------------------------------- Running tests/02_exception_sync_page_fault.rs (target/aarch64-unknown-none-softfloat/release/deps/02_exception_sync_page_fault-2d8ec603ef1c4d8e) ------------------------------------------------------------------- 🦀 Testing synchronous exception handling by causing a page fault ------------------------------------------------------------------- [ 0.132792] Writing beyond mapped area to address 9 GiB... [ 0.134563] Kernel panic! Panic location: File 'src/_arch/aarch64/exception.rs', line 58, column 5 CPU Exception! ESR_EL1: 0x96000004 Exception Class (EC) : 0x25 - Data Abort, current EL [...] ------------------------------------------------------------------- ✅ Success: 02_exception_sync_page_fault.rs ------------------------------------------------------------------- Running tests/03_exception_restore_sanity.rs (target/aarch64-unknown-none-softfloat/release/deps/03_exception_restore_sanity-a56e14285bb26e0e) ------------------------------------------------------------------- 🦀 Running 1 console I/O tests ------------------------------------------------------------------- 1. Exception restore.........................................[ok] Console log: Testing exception restore [ 0.130757] Making a dummy system call [ 0.132592] Back from system call! ------------------------------------------------------------------- ✅ Success: 03_exception_restore_sanity.rs ------------------------------------------------------------------- ``` ## Diff to previous The diff in this tutorial is skipped, because due to the changes in top-level folder structure, it becomes unreadable. This might be fixed in the future. For now, consider using a diff tool like `meld` to diff between the previous and the `kernel` folder of this tutorial to see the lion's share of changes: ```console meld 11_exceptions_part1_groundwork 12_integrated_testing/kernel ``` ================================================ FILE: 12_integrated_testing/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 12_integrated_testing/kernel/build.rs ================================================ 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())); } ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prepares the transition from EL2 to EL1. /// /// # Safety /// /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. /// /// # Safety /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. x0 holds the function argument provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::asynchronous::arch_asynchronous use aarch64_cpu::registers::*; use tock_registers::interfaces::Readable; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- trait DaifField { fn daif_field() -> tock_registers::fields::Field; } struct Debug; struct SError; struct IRQ; struct FIQ; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl DaifField for Debug { fn daif_field() -> tock_registers::fields::Field { DAIF::D } } impl DaifField for SError { fn daif_field() -> tock_registers::fields::Field { DAIF::A } } impl DaifField for IRQ { fn daif_field() -> tock_registers::fields::Field { DAIF::I } } impl DaifField for FIQ { fn daif_field() -> tock_registers::fields::Field { DAIF::F } } fn is_masked() -> bool where T: DaifField, { DAIF.is_set(T::daif_field()) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Print the AArch64 exceptions status. #[rustfmt::skip] pub fn print_state() { use crate::info; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; info!(" Debug: {}", to_mask_str(is_masked::())); info!(" SError: {}", to_mask_str(is_masked::())); info!(" IRQ: {}", to_mask_str(is_masked::())); info!(" FIQ: {}", to_mask_str(is_masked::())); } ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Architectural synchronous and asynchronous exception handling. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::exception::arch_exception use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; use tock_registers::{ interfaces::{Readable, Writeable}, registers::InMemoryRegister, }; // Assembly counterpart to this file. global_asm!(include_str!("exception.s")); //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Wrapper structs for memory copies of registers. #[repr(transparent)] struct SpsrEL1(InMemoryRegister); struct EsrEL1(InMemoryRegister); /// The exception context as it is stored on the stack on exception entry. #[repr(C)] struct ExceptionContext { /// General Purpose Registers. gpr: [u64; 30], /// The link register, aka x30. lr: u64, /// Exception link register. The program counter at the time the exception happened. elr_el1: u64, /// Saved program status. spsr_el1: SpsrEL1, /// Exception syndrome register. esr_el1: EsrEL1, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prints verbose information about the exception and then panics. fn default_exception_handler(exc: &ExceptionContext) { panic!( "CPU Exception!\n\n\ {}", exc ); } //------------------------------------------------------------------------------ // Current, EL0 //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn current_el0_synchronous(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } #[no_mangle] extern "C" fn current_el0_irq(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } #[no_mangle] extern "C" fn current_el0_serror(_e: &mut ExceptionContext) { panic!("Should not be here. Use of SP_EL0 in EL1 is not supported.") } //------------------------------------------------------------------------------ // Current, ELx //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { #[cfg(feature = "test_build")] { const TEST_SVC_ID: u64 = 0x1337; if let Some(ESR_EL1::EC::Value::SVC64) = e.esr_el1.exception_class() { if e.esr_el1.iss() == TEST_SVC_ID { return; } } } default_exception_handler(e); } #[no_mangle] extern "C" fn current_elx_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } //------------------------------------------------------------------------------ // Lower, AArch64 //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } //------------------------------------------------------------------------------ // Lower, AArch32 //------------------------------------------------------------------------------ #[no_mangle] extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } //------------------------------------------------------------------------------ // Misc //------------------------------------------------------------------------------ /// Human readable SPSR_EL1. #[rustfmt::skip] impl fmt::Display for SpsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Raw value. writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; let to_flag_str = |x| -> _ { if x { "Set" } else { "Not set" } }; writeln!(f, " Flags:")?; writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; writeln!(f, " Exception handling state:")?; writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; write!(f, " Illegal Execution State (IL): {}", to_flag_str(self.0.is_set(SPSR_EL1::IL)) ) } } impl EsrEL1 { #[inline(always)] fn exception_class(&self) -> Option { self.0.read_as_enum(ESR_EL1::EC) } #[cfg(feature = "test_build")] #[inline(always)] fn iss(&self) -> u64 { self.0.read(ESR_EL1::ISS) } } /// Human readable ESR_EL1. #[rustfmt::skip] impl fmt::Display for EsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Raw print of whole register. writeln!(f, "ESR_EL1: {:#010x}", self.0.get())?; // Raw print of exception class. write!(f, " Exception Class (EC) : {:#x}", self.0.read(ESR_EL1::EC))?; // Exception class. let ec_translation = match self.exception_class() { Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", _ => "N/A", }; writeln!(f, " - {}", ec_translation)?; // Raw print of instruction specific syndrome. write!(f, " Instr Specific Syndrome (ISS): {:#x}", self.0.read(ESR_EL1::ISS)) } } impl ExceptionContext { #[inline(always)] fn exception_class(&self) -> Option { self.esr_el1.exception_class() } #[inline(always)] fn fault_address_valid(&self) -> bool { use ESR_EL1::EC::Value::*; match self.exception_class() { None => false, Some(ec) => matches!( ec, InstrAbortLowerEL | InstrAbortCurrentEL | PCAlignmentFault | DataAbortLowerEL | DataAbortCurrentEL | WatchpointLowerEL | WatchpointCurrentEL ), } } } /// Human readable print of the exception context. impl fmt::Display for ExceptionContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{}", self.esr_el1)?; if self.fault_address_valid() { writeln!(f, "FAR_EL1: {:#018x}", FAR_EL1.get() as usize)?; } writeln!(f, "{}", self.spsr_el1)?; writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; writeln!(f)?; writeln!(f, "General purpose register:")?; #[rustfmt::skip] let alternating = |x| -> _ { if x % 2 == 0 { " " } else { "\n" } }; // Print two registers per line. for (i, reg) in self.gpr.iter().enumerate() { write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; } write!(f, " lr : {:#018x}", self.lr) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use crate::exception::PrivilegeLevel; /// The processing element's current privilege level. pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { let el = CurrentEL.read_as_enum(CurrentEL::EL); match el { Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), _ => (PrivilegeLevel::Unknown, "Unknown"), } } /// Init exception handling by setting the exception vector base address register. /// /// # Safety /// /// - Changes the HW state of the executing core. /// - The vector table and the symbol `__exception_vector_table_start` from the linker script must /// adhere to the alignment and size constraints demanded by the ARMv8-A Architecture Reference /// Manual. pub unsafe fn handling_init() { // Provided by exception.S. extern "Rust" { static __exception_vector_start: UnsafeCell<()>; } VBAR_EL1.set(__exception_vector_start.get() as u64); // Force VBAR update to complete before next instruction. barrier::isb(barrier::SY); } ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::translation_table::arch_translation_table use crate::{ bsp, memory, memory::mmu::{ arch_mmu::{Granule512MiB, Granule64KiB}, AccessPermissions, AttributeFields, MemAttributes, }, }; use core::convert; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, registers::InMemoryRegister, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. register_bitfields! {u64, STAGE1_TABLE_DESCRIPTOR [ /// Physical address of the next descriptor. NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] TYPE OFFSET(1) NUMBITS(1) [ Block = 0, Table = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } // A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. register_bitfields! {u64, STAGE1_PAGE_DESCRIPTOR [ /// Unprivileged execute-never. UXN OFFSET(54) NUMBITS(1) [ False = 0, True = 1 ], /// Privileged execute-never. PXN OFFSET(53) NUMBITS(1) [ False = 0, True = 1 ], /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] /// Access flag. AF OFFSET(10) NUMBITS(1) [ False = 0, True = 1 ], /// Shareability field. SH OFFSET(8) NUMBITS(2) [ OuterShareable = 0b10, InnerShareable = 0b11 ], /// Access Permissions. AP OFFSET(6) NUMBITS(2) [ RW_EL1 = 0b00, RW_EL1_EL0 = 0b01, RO_EL1 = 0b10, RO_EL1_EL0 = 0b11 ], /// Memory attributes index into the MAIR_EL1 register. AttrIndx OFFSET(2) NUMBITS(3) [], TYPE OFFSET(1) NUMBITS(1) [ Reserved_Invalid = 0, Page = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } /// A table descriptor for 64 KiB aperture. /// /// The output points to the next table. #[derive(Copy, Clone)] #[repr(C)] struct TableDescriptor { value: u64, } /// A page descriptor with 64 KiB aperture. /// /// The output points to physical memory. #[derive(Copy, Clone)] #[repr(C)] struct PageDescriptor { value: u64, } trait StartAddr { fn phys_start_addr_u64(&self) -> u64; fn phys_start_addr_usize(&self) -> usize; } const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB /// aligned, so the lvl3 is put first. #[repr(C)] #[repr(align(65536))] pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], } /// A translation table type for the kernel space. pub type KernelTranslationTable = FixedSizeTranslationTable; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- // The binary is still identity mapped, so we don't need to convert here. impl StartAddr for [T; N] { fn phys_start_addr_u64(&self) -> u64 { self as *const T as u64 } fn phys_start_addr_usize(&self) -> usize { self as *const _ as usize } } impl TableDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance pointing to the supplied address. pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; val.write( STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + STAGE1_TABLE_DESCRIPTOR::VALID::True, ); TableDescriptor { value: val.get() } } } /// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. impl convert::From for tock_registers::fields::FieldValue { fn from(attribute_fields: AttributeFields) -> Self { // Memory attributes. let mut desc = match attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => { STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) } MemAttributes::Device => { STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) } }; // Access Permissions. desc += match attribute_fields.acc_perms { AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, }; // The execute-never attribute is mapped to PXN in AArch64. desc += if attribute_fields.execute_never { STAGE1_PAGE_DESCRIPTOR::PXN::True } else { STAGE1_PAGE_DESCRIPTOR::PXN::False }; // Always set unprivileged exectue-never as long as userspace is not implemented yet. desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; desc } } impl PageDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance. pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; val.write( STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + STAGE1_PAGE_DESCRIPTOR::AF::True + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + STAGE1_PAGE_DESCRIPTOR::VALID::True + (*attribute_fields).into(), ); Self { value: val.get() } } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl FixedSizeTranslationTable { /// Create an instance. pub const fn new() -> Self { // Can't have a zero-sized address space. assert!(NUM_TABLES > 0); Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], } } /// Iterates over all static translation table entries and fills them at once. /// /// # Safety /// /// - Modifies a `static mut`. Ensure it only happens from here. pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { *l2_entry = TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); let (phys_output_addr, attribute_fields) = bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); } } Ok(()) } /// The translation table's base address to be used for programming the MMU. pub fn phys_base_address(&self) -> u64 { self.lvl2.phys_start_addr_u64() } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Check if the size of `struct TableDescriptor` is as expected. #[kernel_test] fn size_of_tabledescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } /// Check if the size of `struct PageDescriptor` is as expected. #[kernel_test] fn size_of_pagedescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } } ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::arch_mmu use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Memory Management Unit type. struct MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; /// Constants for indexing the MAIR_EL1. #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. /// /// # Safety /// /// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); static MMU: MemoryManagementUnit = MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AddressSpace { /// Checks for architectural restrictions. pub const fn arch_address_space_size_sanity_checks() { // Size must be at least one full 512 MiB table. assert!((AS_SIZE % Granule512MiB::SIZE) == 0); // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 // version. assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } /// Configure various settings of stage 1 of the EL1 translation regime. fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the MMU instance. pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use memory::mmu::MMUEnableError; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } // Fail early if translation granule is not supported. if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } // Prepare the memory attribute indirection register. self.set_up_mair(); // Populate translation tables. KERNEL_TABLES .populate_tt_entries() .map_err(MMUEnableError::Other)?; // Set the "Translation Table Base Register". TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); self.configure_translation_control(); // Switch the MMU on. // // First, force all previous changes to be seen before the MMU is enabled. barrier::isb(barrier::SY); // Enable the MMU and turn on data and instruction caching. SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); // Force MMU init to complete before next instruction. barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use core::{cell::UnsafeCell, ops::Range}; use test_macros::kernel_test; /// Check if KERNEL_TABLES is in .bss. #[kernel_test] fn kernel_tables_in_bss() { extern "Rust" { static __bss_start: UnsafeCell; static __bss_end_exclusive: UnsafeCell; } let bss_range = unsafe { Range { start: __bss_start.get(), end: __bss_end_exclusive.get(), } }; let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; assert!(bss_range.contains(&kernel_tables_addr)); } } ================================================ FILE: 12_integrated_testing/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: 12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: 12_integrated_testing/kernel/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: 12_integrated_testing/kernel/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: 12_integrated_testing/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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); } ================================================ FILE: 12_integrated_testing/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW * * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. * It doesn't mean all of them need actually be loaded. */ PHDRS { segment_boot_core_stack PT_LOAD FLAGS(6); segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); } SECTIONS { . = __rpi_phys_dram_start_addr; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : { /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __code_start = .; .text : { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ *(.text._start_rust) /* The Rust entry point */ *(.text*) /* Everything else */ } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { __bss_start = .; *(.bss*); . = ALIGN(16); __bss_end_exclusive = .; } :segment_data /*********************************************************************************************** * Misc ***********************************************************************************************/ .got : { *(.got*) } ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") /DISCARD/ : { *(.comment*) } } ================================================ FILE: 12_integrated_testing/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. use super::map as memory_map; use crate::memory::mmu::*; use core::ops::RangeInclusive; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The kernel's address space defined by this BSP. pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; const NUM_MEM_RANGES: usize = 2; /// The virtual memory layout. /// /// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. /// It is agnostic of the paging granularity that the architecture's MMU will use. pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( memory_map::END_INCLUSIVE, [ TranslationDescriptor { name: "Kernel code and RO data", virtual_range: code_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadOnly, execute_never: false, }, }, TranslationDescriptor { name: "Device MMIO", virtual_range: mmio_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, }, ], ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- fn code_range_inclusive() -> RangeInclusive { // Notice the subtraction to turn the exclusive end into an inclusive end. #[allow(clippy::range_minus_one)] RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) } fn mmio_range_inclusive() -> RangeInclusive { RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the virtual memory layout. pub fn virt_mem_layout() -> &'static KernelVirtualLayout { &LAYOUT } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Check alignment of the kernel's virtual memory layout sections. #[kernel_test] fn virt_mem_layout_sections_are_64KiB_aligned() { const SIXTYFOUR_KIB: usize = 65536; for i in LAYOUT.inner().iter() { let start: usize = *(i.virtual_range)().start(); let end: usize = *(i.virtual_range)().end() + 1; assert_eq!(start % SIXTYFOUR_KIB, 0); assert_eq!(end % SIXTYFOUR_KIB, 0); assert!(end >= start); } } /// Ensure the kernel's virtual memory layout is free of overlaps. #[kernel_test] fn virt_mem_layout_has_no_overlaps() { let layout = virt_mem_layout().inner(); for (i, first) in layout.iter().enumerate() { for second in layout.iter().skip(i + 1) { let first_range = first.virtual_range; let second_range = second.virtual_range; assert!(!first_range().contains(second_range().start())); assert!(!first_range().contains(second_range().end())); assert!(!second_range().contains(first_range().start())); assert!(!second_range().contains(first_range().end())); } } } } ================================================ FILE: 12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! //! The physical memory layout. //! //! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used //! as the boot core's stack. //! //! +---------------------------------------+ //! | | 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | //! | | pub mod mmu; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // Symbols from the linker script. extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { /// The inclusive end address of the memory map. /// /// End address + 1 must be power of two. /// /// # Note /// /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. /// /// However, making this trade-off has the downside of making it possible for the CPU to assert a /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const END_INCLUSIVE: usize = 0x4000_FFFF; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const END_INCLUSIVE: usize = 0xFF84_FFFF; } } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Start page address of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_start() -> usize { unsafe { __code_start.get() as usize } } /// Exclusive end page address of the code segment. /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_end_exclusive() -> usize { unsafe { __code_end_exclusive.get() as usize } } ================================================ FILE: 12_integrated_testing/kernel/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Board identification. pub fn board_name() -> &'static str { #[cfg(feature = "bsp_rpi3")] { "Raspberry Pi 3" } #[cfg(feature = "bsp_rpi4")] { "Raspberry Pi 4" } } ================================================ FILE: 12_integrated_testing/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 12_integrated_testing/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 12_integrated_testing/kernel/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 12_integrated_testing/kernel/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: 12_integrated_testing/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 12_integrated_testing/kernel/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; #[cfg(feature = "test_build")] pub use arch_cpu::{qemu_exit_failure, qemu_exit_success}; ================================================ FILE: 12_integrated_testing/kernel/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 12_integrated_testing/kernel/src/exception/asynchronous.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Asynchronous exception handling. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/exception/asynchronous.rs"] mod arch_asynchronous; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_asynchronous::print_state; ================================================ FILE: 12_integrated_testing/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 12_integrated_testing/kernel/src/lib.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` library. //! //! Used to compose the final kernel binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![allow(incomplete_features)] #![feature(asm_const)] #![feature(const_option)] #![feature(core_intrinsics)] #![feature(format_args_nl)] #![feature(int_roundings)] #![feature(linkage)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_std] // Testing #![cfg_attr(test, no_main)] #![feature(custom_test_frameworks)] #![reexport_test_harness_main = "test_main"] #![test_runner(crate::test_runner)] mod panic_wait; mod synchronization; pub mod bsp; pub mod common; pub mod console; pub mod cpu; pub mod driver; pub mod exception; pub mod memory; pub mod print; pub mod time; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Version string. pub fn version() -> &'static str { concat!( env!("CARGO_PKG_NAME"), " version ", env!("CARGO_PKG_VERSION") ) } #[cfg(not(test))] extern "Rust" { fn kernel_init() -> !; } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- /// The default runner for unit tests. pub fn test_runner(tests: &[&test_types::UnitTest]) { // This line will be printed as the test header. println!("Running {} tests", tests.len()); for (i, test) in tests.iter().enumerate() { print!("{:>3}. {:.<58}", i + 1, test.name); // Run the actual test. (test.test_func)(); // Failed tests call panic!(). Execution reaches here only if the test has passed. println!("[ok]") } } /// The `kernel_init()` for unit tests. #[cfg(test)] #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); bsp::driver::qemu_bring_up_console(); test_main(); cpu::qemu_exit_success() } ================================================ FILE: 12_integrated_testing/kernel/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. #![feature(format_args_nl)] #![no_main] #![no_std] use libkernel::{bsp, console, driver, exception, info, memory, time}; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order: /// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, /// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ /// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { panic!("MMU: {}", string); } // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { use console::console; info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); info!("MMU online. Special regions:"); bsp::memory::mmu::virt_mem_layout().print_layout(); let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); info!("Exception handling state:"); exception::asynchronous::print_state(); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); info!("Echoing input now"); // Discard any spurious received characters before going into echo mode. console().clear_rx(); loop { let c = console().read_char(); console().write_char(c); } } ================================================ FILE: 12_integrated_testing/kernel/src/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Translation table. #[cfg(target_arch = "aarch64")] #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] mod arch_translation_table; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_translation_table::KernelTranslationTable; ================================================ FILE: 12_integrated_testing/kernel/src/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! //! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file //! provides types for composing an architecture-agnostic description of the kernel's virtual memory //! layout. //! //! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` //! function. //! //! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and //! install respective translation tables. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; mod translation_table; use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_mmu::mmu; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// MMU enable errors variants. #[allow(missing_docs)] #[derive(Debug)] pub enum MMUEnableError { AlreadyEnabled, Other(&'static str), } /// Memory Management interfaces. pub mod interface { use super::*; /// MMU functions. pub trait MMU { /// Called by the kernel during early init. Supposed to take the translation tables from the /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. /// /// # Safety /// /// - Changes the HW's global state. unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; } } /// Describes the characteristics of a translation granule. pub struct TranslationGranule; /// Describes properties of an address space. pub struct AddressSpace; /// Architecture agnostic translation types. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum Translation { Identity, Offset(usize), } /// Architecture agnostic memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum MemAttributes { CacheableDRAM, Device, } /// Architecture agnostic access permissions. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum AccessPermissions { ReadOnly, ReadWrite, } /// Collection of memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, pub execute_never: bool, } /// Architecture agnostic descriptor for a memory range. #[allow(missing_docs)] pub struct TranslationDescriptor { pub name: &'static str, pub virtual_range: fn() -> RangeInclusive, pub physical_range_translation: Translation, pub attribute_fields: AttributeFields, } /// Type for expressing the kernel's virtual memory layout. pub struct KernelVirtualLayout { /// The last (inclusive) address of the address space. max_virt_addr_inclusive: usize, /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl fmt::Display for MMUEnableError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), MMUEnableError::Other(x) => write!(f, "{}", x), } } } impl TranslationGranule { /// The granule's size. pub const SIZE: usize = Self::size_checked(); /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(GRANULE_SIZE.is_power_of_two()); GRANULE_SIZE } } impl AddressSpace { /// The address space size. pub const SIZE: usize = Self::size_checked(); /// The address space shift, aka log2(size). pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(AS_SIZE.is_power_of_two()); // Check for architectural restrictions as well. Self::arch_address_space_size_sanity_checks(); AS_SIZE } } impl Default for AttributeFields { fn default() -> AttributeFields { AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, } } } /// Human-readable output of a TranslationDescriptor. impl fmt::Display for TranslationDescriptor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Call the function to which self.range points, and dereference the result, which causes // Rust to copy the value. let start = *(self.virtual_range)().start(); let end = *(self.virtual_range)().end(); let size = end - start + 1; let (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", MemAttributes::Device => "Dev", }; let acc_p = match self.attribute_fields.acc_perms { AccessPermissions::ReadOnly => "RO", AccessPermissions::ReadWrite => "RW", }; let xn = if self.attribute_fields.execute_never { "PXN" } else { "PX" }; write!( f, " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", start, end, size, unit, attr, acc_p, xn, self.name ) } } impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { /// Create a new instance. pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { Self { max_virt_addr_inclusive: max, inner: layout, } } /// For a virtual address, find and return the physical output address and corresponding /// attributes. /// /// If the address is not found in `inner`, return an identity mapped default with normal /// cacheable DRAM attributes. pub fn virt_addr_properties( &self, virt_addr: usize, ) -> Result<(usize, AttributeFields), &'static str> { if virt_addr > self.max_virt_addr_inclusive { return Err("Address out of range"); } for i in self.inner.iter() { if (i.virtual_range)().contains(&virt_addr) { let output_addr = match i.physical_range_translation { Translation::Identity => virt_addr, Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), }; return Ok((output_addr, i.attribute_fields)); } } Ok((virt_addr, AttributeFields::default())) } /// Print the memory layout. pub fn print_layout(&self) { use crate::info; for i in self.inner.iter() { info!("{}", i); } } #[cfg(test)] pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { &self.inner } } ================================================ FILE: 12_integrated_testing/kernel/src/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management. pub mod mmu; ================================================ FILE: 12_integrated_testing/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 12_integrated_testing/kernel/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 12_integrated_testing/kernel/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: 12_integrated_testing/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 12_integrated_testing/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 12_integrated_testing/kernel/tests/00_console_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Console sanity tests - RX, TX and statistics. #![feature(format_args_nl)] #![no_main] #![no_std] /// Console tests should time out on the I/O harness in case of panic. mod panic_wait_forever; use libkernel::{bsp, console, cpu, exception, print}; #[no_mangle] unsafe fn kernel_init() -> ! { use console::console; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); assert_eq!(console().read_char(), 'B'); assert_eq!(console().read_char(), 'C'); print!("OK1234"); // 6 print!("{}", console().chars_written()); // 3 print!("{}", console().chars_read()); // The QEMU process running this test will be closed by the I/O test harness. cpu::wait_forever(); } ================================================ FILE: 12_integrated_testing/kernel/tests/01_timer_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. #![feature(custom_test_frameworks)] #![no_main] #![no_std] #![reexport_test_harness_main = "test_main"] #![test_runner(libkernel::test_runner)] use core::time::Duration; use libkernel::{bsp, cpu, exception, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. test_main(); cpu::qemu_exit_success() } /// Simple check that the timer is running. #[kernel_test] fn timer_is_counting() { assert!(time::time_manager().uptime().as_nanos() > 0) } /// Timer resolution must be sufficient. #[kernel_test] fn timer_resolution_is_sufficient() { assert!(time::time_manager().resolution().as_nanos() > 0); assert!(time::time_manager().resolution().as_nanos() < 100) } /// Sanity check spin_for() implementation. #[kernel_test] fn spin_accuracy_check_1_second() { let t1 = time::time_manager().uptime(); time::time_manager().spin_for(Duration::from_secs(1)); let t2 = time::time_manager().uptime(); assert_eq!((t2 - t1).as_secs(), 1) } ================================================ FILE: 12_integrated_testing/kernel/tests/02_exception_sync_page_fault.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. #![feature(format_args_nl)] #![no_main] #![no_std] /// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. /// /// In this test, reaching the panic is a success, because it is called from the synchronous /// exception handler, which is what this test wants to achieve. /// /// It also means that this integration test can not use any other code that calls panic!() directly /// or indirectly. mod panic_exit_success; use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { info!("MMU: {}", string); cpu::qemu_exit_failure() } info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); // If execution reaches here, the memory access above did not cause a page fault exception. cpu::qemu_exit_failure() } ================================================ FILE: 12_integrated_testing/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 12_integrated_testing/kernel/tests/03_exception_restore_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. #![feature(format_args_nl)] #![no_main] #![no_std] /// Console tests should time out on the I/O harness in case of panic. mod panic_wait_forever; use core::arch::asm; use libkernel::{bsp, cpu, exception, info, memory, println}; #[inline(never)] fn nested_system_call() { #[cfg(target_arch = "aarch64")] unsafe { asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); } #[cfg(not(target_arch = "aarch64"))] { info!("Not supported yet"); cpu::wait_forever(); } } #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { info!("MMU: {}", string); cpu::qemu_exit_failure() } info!("Making a dummy system call"); // Calling this inside a function indirectly tests if the link register is restored properly. nested_system_call(); info!("Back from system call!"); // The QEMU process running this test will be closed by the I/O test harness. cpu::wait_forever(); } ================================================ FILE: 12_integrated_testing/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 12_integrated_testing/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 12_integrated_testing/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 12_integrated_testing/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 12_integrated_testing/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 12_integrated_testing/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 12_integrated_testing/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel" ] [profile.release] lto = true ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 # Optional integration test name. ifdef TEST TEST_ARG = --test $(TEST) else TEST_ARG = --test '*' endif ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = kernel/Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot test_unit test_integration test_unit test_integration: FEATURES += --features test_build ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test_unit test_integration test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER #!/usr/bin/env bash # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure # this script executes from the root. cd $(shell pwd) TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY endef export KERNEL_TEST_RUNNER define test_prepare @mkdir -p target @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh @chmod +x target/kernel_test_runner.sh endef ##------------------------------------------------------------------------------ ## Run unit test(s) ##------------------------------------------------------------------------------ test_unit: $(call color_header, "Compiling unit test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib ##------------------------------------------------------------------------------ ## Run integration test(s) ##------------------------------------------------------------------------------ test_integration: $(call color_header, "Compiling integration test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) test: test_boot test_unit test_integration endif ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/README.md ================================================ # Tutorial 13 - Exceptions Part 2: Peripheral IRQs ## tl;dr - We write `device drivers` for the two interrupt controllers on the **Raspberry Pi 3** (`Broadcom` custom controller) and **Pi 4** (`ARM` Generic Interrupt Controller v2, `GICv2`). - Modularity is ensured by interfacing everything through a trait named `IRQManager`. - Handling for our first peripheral IRQs is implemented: The `UART`'s receive IRQs. ![Header](../doc/14_header.png) ## Table of Contents - [Introduction](#introduction) - [Different Controllers: A Usecase for Abstraction](#different-controllers-a-usecase-for-abstraction) - [New Challenges: Reentrancy](#new-challenges-reentrancy) - [Implementation](#implementation) * [The Kernel's Interfaces for Interrupt Handling](#the-kernels-interfaces-for-interrupt-handling) + [Uniquely Identifying an IRQ](#uniquely-identifying-an-irq) - [The BCM IRQ Number Scheme](#the-bcm-irq-number-scheme) - [The GICv2 IRQ Number Scheme](#the-gicv2-irq-number-scheme) + [Registering IRQ Handlers](#registering-irq-handlers) + [Handling Pending IRQs](#handling-pending-irqs) * [Reentrancy: What to protect?](#reentrancy-what-to-protect) * [The Interrupt Controller Device Drivers](#the-interrupt-controller-device-drivers) + [The BCM Driver (Pi 3)](#the-bcm-driver-pi-3) - [Peripheral Controller Register Access](#peripheral-controller-register-access) - [The IRQ Handler Table](#the-irq-handler-table) + [The GICv2 Driver (Pi 4)](#the-gicv2-driver-pi-4) - [GICC Details](#gicc-details) - [GICD Details](#gicd-details) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction In [tutorial 11], we laid the groundwork for exception handling from the processor architecture side. Handler stubs for the different exception types were set up, and a first glimpse at exception handling was presented by causing a `synchronous` exception by means of a `page fault`. [tutorial 11]: ../11_exceptions_part1_groundwork In this tutorial, we will add a first level of support for one of the three types of `asynchronous` exceptions that are defined for `AArch64`: `IRQs`. The overall goal for this tutorial is to get rid of the busy-loop at the end of our current `kernel_main()` function, which actively polls the `UART` for newly received characters. Instead, we will let the processor idle and wait for the `UART`'s RX IRQs, which indicate that new characters were received. A respective `IRQ` service routine, provided by the `UART` driver, will run in response to the `IRQ` and print the characters. ## Different Controllers: A Usecase for Abstraction One very exciting aspect of this tutorial is that the `Pi 3` and the `Pi 4` feature completely different interrupt controllers. This is also a first in all of the tutorial series. Until now, both Raspberrys did not need differentiation with respect to their devices. The `Pi 3` has a very simple custom controller made by Broadcom (BCM), the manufacturer of the Pi's `System-on-Chip`. The `Pi 4` features an implementation of `ARM`'s Generic Interrupt Controller version 2 (`GICv2`). Since ARM's GIC controllers are the prevalent interrupt controllers in ARM application procesors, it is very beneficial to finally have it on the Raspberry Pi. It will enable people to learn about one of the most common building blocks in ARM-based embedded computing. This also means that we can finally make full use of all the infrastructure for abstraction that we prepared already. We will design an `IRQManager` interface trait and implement it in both controller drivers. The generic part of our `kernel` code will only be exposed to this trait (compare to the diagram in the [tl;dr] section). This common idiom of *program to an interface, not an implementation* enables a clean abstraction and makes the code modular and pluggable. [tl;dr]: #tldr ## New Challenges: Reentrancy Enabling interrupts also poses new challenges with respect to protecting certain code sections in the kernel from being [re-entered]. Please read the linked article for background on that topic. [re-entered]: https://en.wikipedia.org/wiki/Reentrancy_(computing) Our `kernel` is still running on a single core. For this reason, we are still using our `NullLock` pseudo-locks for `Critical Sections` or `shared resources`, instead of real `Spinlocks`. Hence, interrupt handling at this point in time does not put us at risk of running into one of those dreaded `deadlocks`, which is one of several side-effects that reentrancy can cause. For example, a `deadlock` because of interrupts can happen happen when the executing CPU core has locked a `Spinlock` at the beginning of a function, an IRQ happens, and the IRQ service routine is trying to execute the same function. Since the lock is already locked, the core would spin forever waiting for it to be released. There is no straight-forward way to tell if a function is `reentrantcy`-safe or not. It usually needs careful manual checking to conclude. Even though it might be technically safe to `re-enter` a function, sometimes you don't want that to happen for functional reasons. For example, printing of a string should not be interrupted by a an interrupt service routine that starts printing another string, so that the output mixes. In the course of this tutorial, we will check and see where we want to protect against `reentrancy`. ## Implementation Okay, let's start. The following sections cover the the implementation in a top-down fashion, starting with the trait that interfaces all the `kernel` components to each other. ### The Kernel's Interfaces for Interrupt Handling First, we design the `IRQManager` trait that interrupt controller drivers must implement. The minimal set of functionality that we need for starters is: 1. Registering an IRQ `handler` for a given IRQ `number`. 2. Enabling an IRQ (from the controller side). 3. Handling pending IRQs. 4. Printing the list of registered IRQ handlers. The trait is defined as `exception::asynchronous::interface::IRQManager`: ```rust pub trait IRQManager { /// The IRQ number type depends on the implementation. type IRQNumberType: Copy; /// Register a handler. fn register_handler( &self, irq_handler_descriptor: super::IRQHandlerDescriptor, ) -> Result<(), &'static str>; /// Enable an interrupt in the controller. fn enable(&self, irq_number: &Self::IRQNumberType); /// Handle pending interrupts. /// /// This function is called directly from the CPU's IRQ exception vector. On AArch64, /// this means that the respective CPU core has disabled exception handling. /// This function can therefore not be preempted and runs start to finish. /// /// Takes an IRQContext token to ensure it can only be called from IRQ context. #[allow(clippy::trivially_copy_pass_by_ref)] fn handle_pending_irqs<'irq_context>( &'irq_context self, ic: &super::IRQContext<'irq_context>, ); /// Print list of registered handlers. fn print_handler(&self) {} } ``` #### Uniquely Identifying an IRQ The first member of the trait is the [associated type] `IRQNumberType`. The following explains why we make it customizable for the implementor and do not define the type as a plain integer right away. Interrupts can generally be characterizied with the following properties: [associated type]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#specifying-placeholder-types-in-trait-definitions-with-associated-types 1. Software-generated vs hardware-generated. 2. Private vs shared. Different interrupt controllers take different approaches at categorizing and numbering IRQs that have one or the other property. Often times, this leads to situations where a plain integer does not suffice to uniquely identify an IRQ, and makes it necessary to encode additional information in the used type. Letting the respective interrupt controller driver define `IRQManager::IRQNumberType` itself addresses this issue. The rest of the `BSP` must then conditionally use this type. ##### The BCM IRQ Number Scheme The `BCM` controller of the `Raspberry Pi 3`, for example, is composed of two functional parts: A **local** controller and a **peripheral** controller. The BCM's **local controller** handles all `private` IRQs, which means private SW-generated IRQs and IRQs of private HW devices. An example for the latter would be the `ARMv8` timer. Each CPU core has its own private instance of it. The BCM's **peripheral controller** handles all IRQs of `non-private` HW devices such as the `UART` (if those IRQs can be declared as `shared` according to our taxonomy above is a different discussion, because the BCM controller allows these HW interrupts to be routed to _only one CPU core at a time_). The IRQ numbers of the BCM **local controller** range from `0..11`. The numbers of the **peripheral controller** range from `0..63`. This demonstrates why a primitive integer type would not be sufficient to uniquely encode the IRQs, because their ranges overlap. In the driver for the `BCM` controller, we therefore define the associated type as follows: ```rust pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. #[derive(Copy, Clone)] #[allow(missing_docs)] pub enum IRQNumber { Local(LocalIRQ), Peripheral(PeripheralIRQ), } ``` The type `BoundedUsize` is a newtype around an `usize` that uses a [const generic] to ensure that the value of the encapsulated IRQ number is in the allowed range (e.g. `0..MAX_LOCAL_IRQ_NUMBER` for `LocalIRQ`, with `MAX_LOCAL_IRQ_NUMBER == 11`). [const generic]: https://github.com/rust-lang/rfcs/blob/master/text/2000-const-generics.md ##### The GICv2 IRQ Number Scheme The `GICv2` in the `Raspberry Pi 4`, on the other hand, uses a different scheme. IRQ numbers `0..31` are for `private` IRQs. Those are further subdivided into `SW-generated` (SGIs, `0..15`) and `HW-generated` (PPIs, Private Peripheral Interrupts, `16..31`). Numbers `32..1019` are for `shared hardware-generated` interrupts (SPI, Shared Peripheral Interrupts). There are no overlaps, so this scheme enables us to actually have a plain integer as a unique identifier for the IRQs. We define the type as follows: ```rust /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; ``` #### Registering IRQ Handlers To enable the controller driver to manage interrupt handling, it must know where to find respective handlers, and it must know how to call them. For the latter, we define an `IRQHandler` trait in `exception::asynchronous` that must be implemented by any SW entity that wants to handle IRQs: ```rust /// Implemented by types that handle IRQs. pub trait IRQHandler { /// Called when the corresponding interrupt is asserted. fn handle(&self) -> Result<(), &'static str>; } ``` The `PL011Uart` driver gets the honors for being our first driver to ever implement this trait. In this tutorial, the `RX IRQ` and the `RX Timeout IRQ` will be configured. This means that the `PL011Uart` will assert it's interrupt line when one of following conditions is met: 1. `RX IRQ`: The RX FIFO fill level is equal or more than the configured trigger level (which will be 1/8 of the total FIFO size in our case). 1. `RX Timeout IRQ`: The RX FIFO fill level is greater than zero, but less than the configured fill level, and the characters have not been pulled for a certain amount of time. The exact time is not documented in the respective `PL011Uart` datasheet. Usually, it is a single-digit multiple of the time it takes to receive or transmit one character on the serial line. In the handler, our standard scheme of echoing any received characters back to the host is used: ```rust impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { let pending = inner.registers.MIS.extract(); // Clear all pending IRQs. inner.registers.ICR.write(ICR::ALL::CLEAR); // Check for any kind of RX interrupt. if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { // Echo any received characters. while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { inner.write_char(c) } } }); Ok(()) } } ``` Registering and enabling handlers in the interrupt controller is supposed to be done by the respective drivers themselves. Therefore, we added a new function to the standard device driver trait in `driver::interface::DeviceDriver` that must be implemented if IRQ handling is supported: ```rust /// Called by the kernel to register and enable the device's IRQ handler. /// /// Rust's type system will prevent a call to this function unless the calling instance /// itself has static lifetime. fn register_and_enable_irq_handler( &'static self, irq_number: &Self::IRQNumberType, ) -> Result<(), &'static str> { panic!( "Attempt to enable IRQ {} for device {}, but driver does not support this", irq_number, self.compatible() ) } ``` Here is the implementation for the `PL011Uart`: ```rust fn register_and_enable_irq_handler( &'static self, irq_number: &Self::IRQNumberType, ) -> Result<(), &'static str> { use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); irq_manager().register_handler(descriptor)?; irq_manager().enable(irq_number); Ok(()) } ``` The `exception::asynchronous::irq_manager()` function used here returns a reference to an implementor of the `IRQManager` trait. Since the implementation is supposed to be done by the platform's interrupt controller, this call will redirect to the `kernel`'s instance of either the driver for the `BCM` controller (`Raspberry Pi 3`) or the driver for the `GICv2` (`Pi 4`). We will look into the implementation of the `register_handler()` function from the driver's perspective later. The gist here is that the calls on `irq_manager()` will make the platform's interrupt controller aware that the `UART` driver (i) wants to handle its interrupt and (ii) which function it provides to do so. Also note how `irq_number` is supplied as a function argument and not hardcoded. The reason is that the `UART` driver code is agnostic about the **IRQ numbers** that are associated to it. This is vendor-supplied information and as such typically part of the Board Support Package (`BSP`). It can vary from `BSP` to `BSP`, same like the board's memory map, which provides the `UART`'s MMIO register addresses. With all this in place, we can finally let drivers register and enable their IRQ handlers with the interrupt controller, and unmask IRQ reception on the boot CPU core during the kernel init phase. The global `driver_manager` takes care of this in the function `init_drivers_and_irqs()` (before this tutorial, the function's name was `init_drivers()`), where this happens as the third and last step of initializing all registered device drivers: ```rust pub unsafe fn init_drivers_and_irqs(&self) { self.for_each_descriptor(|descriptor| { // 1. Initialize driver. if let Err(x) = descriptor.device_driver.init() { // omitted for brevity } // 2. Call corresponding post init callback. if let Some(callback) = &descriptor.post_init_callback { // omitted for brevity } }); // 3. After all post-init callbacks were done, the interrupt controller should be // registered and functional. So let drivers register with it now. self.for_each_descriptor(|descriptor| { if let Some(irq_number) = &descriptor.irq_number { if let Err(x) = descriptor .device_driver .register_and_enable_irq_handler(irq_number) { panic!( "Error during driver interrupt handler registration: {}: {}", descriptor.device_driver.compatible(), x ); } } }); } ``` In `main.rs`, IRQs are unmasked right afterwards, after which point IRQ handling is live: ```rust // Initialize all device drivers. driver::driver_manager().init_drivers_and_irqs(); // Unmask interrupts on the boot CPU core. exception::asynchronous::local_irq_unmask(); ``` #### Handling Pending IRQs Now that interrupts can happen, the `kernel` needs a way of requesting the interrupt controller driver to handle pending interrupts. Therefore, implementors of the trait `IRQManager` must also supply the following function: ```rust fn handle_pending_irqs<'irq_context>( &'irq_context self, ic: &super::IRQContext<'irq_context>, ); ``` An important aspect of this function signature is that we want to ensure that IRQ handling is only possible from IRQ context. Part of the reason is that this invariant allows us to make some implicit assumptions (which might depend on the target architecture, though). For example, as we have learned in [tutorial 11], in `AArch64`, _"all kinds of exceptions are turned off upon taking an exception, so that by default, exception handlers can not get interrupted themselves"_ (note that an IRQ is an exception). This is a useful property that relieves us from explicitly protecting IRQ handling from being interrupted itself. Another reason would be that calling IRQ handling functions from arbitrary execution contexts just doesn't make a lot of sense. [tutorial 11]: ../11_exceptions_part1_groundwork/ So in order to ensure that this function is only being called from IRQ context, we borrow a technique that I first saw in the [Rust embedded WG]'s [bare-metal crate]. It uses Rust's type system to create a "token" that is only valid for the duration of the IRQ context. We create it directly at the top of the IRQ vector function in `_arch/aarch64/exception.rs`, and pass it on to the the implementation of the trait's handling function: [Rust embedded WG]: https://github.com/rust-embedded/bare-metal [bare-metal crate]: https://github.com/rust-embedded/bare-metal/blob/master/src/lib.rs#L20 ```rust #[no_mangle] extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { let token = unsafe { &exception::asynchronous::IRQContext::new() }; exception::asynchronous::irq_manager().handle_pending_irqs(token); } ``` By requiring the caller of the function `handle_pending_irqs()` to provide this `IRQContext` token, we can prevent that the same function is accidentally being called from somewhere else. It is evident, though, that for this to work, it is the _user's responsibility_ to only ever create this token from within an IRQ context. If you want to circumvent this on purpose, you can do it. ### Reentrancy: What to protect? Now that interrupt handling is live, we need to think about `reentrancy`. At [the beginning of this tutorial], we mused about the need to protect certain functions from being re-entered, and that it is not straight-forward to identify all the places that need protection. [the beginning of this tutorial]: #new-challenges-reentrancy In this tutorial, we will keep this part short nonetheless by taking a better-safe-than-sorry approach. In the past, we already made efforts to prepare parts of `shared resources` (e.g. global device driver instances) to be protected against parallel access. We did so by wrapping them into `NullLocks`, which we will upgrade to real `Spinlocks` once we boot secondary CPU cores. We can hook on that previous work and reason that anything that we wanted protected against parallel access so far, we also want it protected against reentrancy now. Therefore, we upgrade all `NullLocks` to `IRQSafeNullocks`: ```rust impl interface::Mutex for IRQSafeNullLock { type Data = T; fn lock(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; // Execute the closure while IRQs are masked. exception::asynchronous::exec_with_irq_masked(|| f(data)) } } ``` The new part is that the call to `f(data)` is executed as a closure in `exception::asynchronous::exec_with_irq_masked()`. Inside that function, IRQs on the executing CPU core are masked before the `f(data)` is being executed, and restored afterwards: ```rust /// Executes the provided closure while IRQs are masked on the executing core. /// /// While the function temporarily changes the HW state of the executing core, it restores it to the /// previous state before returning, so this is deemed safe. #[inline(always)] pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { let saved = local_irq_mask_save(); let ret = f(); local_irq_restore(saved); ret } ``` The helper functions used here are defined in `src/_arch/aarch64/exception/asynchronous.rs`. ### The Interrupt Controller Device Drivers The previous sections explained how the `kernel` uses the `IRQManager` trait. Now, let's have a look at the driver-side of it in the Raspberry Pi `BSP`. We start with the Broadcom interrupt controller featured in the `Pi 3`. #### The BCM Driver (Pi 3) As mentioned earlier, the `BCM` driver consists of two subcomponents, a **local** and a **peripheral** controller. The local controller owns a bunch of configuration registers, among others, the `routing` configuration for peripheral IRQs such as those from the `UART`. Peripheral IRQs can be routed to _one core only_. In our case, we leave the default unchanged, which means everything is routed to the boot CPU core. The image below depicts the `struct diagram` of the driver implementation. ![BCM Driver](../doc/14_BCM_driver.png) We have a top-level driver, which implements the `IRQManager` trait. _Only the top-level driver_ is exposed to the rest of the `kernel`. The top-level itself has two members, representing the local and the peripheral controller, respectively, which implement the `IRQManager` trait as well. This design allows for easy forwarding of function calls from the top-level driver to one of the subcontrollers. For this tutorial, we leave out implementation of the local controller, because we will only be concerned with the peripheral `UART` IRQ. ##### Peripheral Controller Register Access When writing a device driver for a kernel with exception handling and multi-core support, it is always important to analyze what parts of the driver will need protection against reentrancy (we talked about this earlier in this tutorial) and/or parallel execution of other driver parts. If a driver function needs to follow a vendor-defined sequence of multiple register operations that include `write operations`, this is usually a good hint that protection might be needed. But that is only one of many examples. For the driver implementation in this tutorial, we are following a simple rule: Register read access is deemed always safe. Write access is guarded by an `IRQSafeNullLock`, which means that we are safe against `reentrancy` issues, and also in the future when the kernel will be running on multiple cores, we can easily upgrade to a real spinlock, which serializes register write operations from different CPU cores. In fact, for this tutorial, we probably would not have needed any protection yet, because all the driver does is read from the `PENDING_*` registers for the `handle_pending_irqs()` implementation, and writing to the `ENABLE_*` registers for the `enable()` implementation. However, the chosen architecture will have us set up for future extensions, when more complex register manipulation sequences might be needed. Since nothing complex is happening in the implementation, it is not covered in detail here. Please refer to [the source of the **peripheral** controller] to check it out. [the source of the **peripheral** controller]: kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ##### The IRQ Handler Table Calls to `register_handler()` result in the driver inserting the provided handler reference in a specific table (the handler reference is a member of `IRQDescriptor`): ```rust type HandlerTable = [Option>; PeripheralIRQ::MAX_INCLUSIVE + 1]; ``` One of the requirements for safe operation of the `kernel` is that those handlers are not registered, removed or exchanged in the middle of an IRQ handling situation. This, again, is a multi-core scenario where one core might look up a handler entry while another core is modifying the same in parallel. While we want to allow drivers to take the decision of registering or not registering a handler at runtime, there is no need to allow it for the _whole_ runtime of the kernel. It is fine to restrict this option to the kernel `init phase`, at which only a single boot core runs and IRQs are masked. We introduce the so called `InitStateLock` for cases like that. From an API-perspective, it is a special variant of a `Read/Write exclusion synchronization primitive`. RWLocks in the Rust standard library [are characterized] as allowing _"a number of readers or at most one writer at any point in time"_. For the `InitStateLock`, we only implement the `read()` and `write()` functions: [are characterized]: https://doc.rust-lang.org/std/sync/struct.RwLock.html ```rust impl interface::ReadWriteEx for InitStateLock { type Data = T; fn write(&self, f: impl FnOnce(&mut Self::Data) -> R) -> R { assert!( state::state_manager().is_init(), "InitStateLock::write called after kernel init phase" ); assert!( !exception::asynchronous::is_local_irq_masked(), "InitStateLock::write called with IRQs unmasked" ); let data = unsafe { &mut *self.data.get() }; f(data) } fn read(&self, f: impl FnOnce(&Self::Data) -> R) -> R { let data = unsafe { &*self.data.get() }; f(data) } } ``` The `write()` function is guarded by two `assertions`. One ensures that IRQs are masked, the other checks the `state::state_manager()` if the kernel is still in the init phase. The `State Manager` is new since this tutorial, and implemented in `src/state.rs`. It provides atomic state transition and reporting functions that are called when the kernel enters a new phase. In the current kernel, the only call is happening before the transition from `kernel_init()` to `kernel_main()`: ```rust // Announce conclusion of the kernel_init() phase. state::state_manager().transition_to_single_core_main(); ``` P.S.: Since the use case for the `InitStateLock` also applies to a few other places in the kernel (for example, registering the system-wide console during early boot), `InitStateLock`s have been incorporated in those other places as well. #### The GICv2 Driver (Pi 4) As we learned earlier, the ARM `GICv2` in the `Raspberry Pi 4` features a continuous interrupt number range: - IRQ numbers `0..31` represent IRQs that are private (aka local) to the respective processor core. - IRQ numbers `32..1019` are for shared IRQs. The `GIC` has a so-called `Distributor`, the `GICD`, and a `CPU Interface`, the `GICC`. The `GICD`, among other things, is used to enable IRQs and route them to one or more CPU cores. The `GICC` is used by CPU cores to check which IRQs are pending, and to acknowledge them once they were handled. There is one dedicated `GICC` for _each CPU core_. One neat thing about the `GICv2` is that any MMIO registers that are associated to core-private IRQs are `banked`. That means that different CPU cores can assert the same MMIO address, but they will end up accessing a core-private copy of the referenced register. This makes it very comfortable to program the `GIC`, because this hardware design ensures that each core only ever gets access to its own resources. Preventing one core to accidentally or willfully fiddle with the IRQ state of another core must therefore not be enforced in software. In summary, this means that any registers in the `GICD` that deal with the core-private IRQ range are banked. Since there is one `GICC` per CPU core, the whole thing is banked. This allows us to design the following `struct diagram` for our driver implementation: ![GICv2 Driver](../doc/14_GICv2_driver.png) The top-level struct is composed of a `GICD`, a `GICC` and a `HandlerTable`. The latter is implemented identically as in the `Pi 3`. ##### GICC Details Since the `GICC` is banked wholly, the top-level driver can directly forward any requests to it, without worrying about concurrency issues for now. Note that this only works as long as the `GICC` implementation is only accessing the banked `GICC` registers, and does not save any state in member variables that are stored in `DRAM`. The two main duties of the `GICC` struct are to read the `IAR` (Interrupt Acknowledge) register, which returns the number of the highest-priority pending IRQ, and writing to the `EOIR` (End Of Interrupt) register, which tells the hardware that handling of an interrupt is now concluded. ##### GICD Details The `GICD` hardware block differentiates between `shared` and `banked` registers. As with the `GICC`, we don't have to protect the banked registers against concurrent access. The shared registers are wrapped into an `IRQSafeNullLock` again. The important parts of the `GICD` for this tutorial are the `ITARGETSR[256]` and `ISENABLER[32]` register arrays. Each `ITARGETSR` is subdivided into four _bytes_. Each byte represents one IRQ, and stores a bitmask that encodes all the `GICCs` to which the respective IRQ is forwarded. For example, `ITARGETSR[0].byte0` would represent IRQ number 0, and `ITARGETSR[0].byte3` IRQ number 3. In the `ISENABLER`, each _bit_ represents an IRQ. For example, `ISENABLER[0].bit3` is IRQ number 3. In summary, this means that `ITARGETSR[0..7]` and `ISENABLER[0]` represent the first 32 IRQs (the banked ones), and as such, we split the register block into `shared` and `banked` parts accordingly in `gicd.rs`: ```rust register_structs! { #[allow(non_snake_case)] SharedRegisterBlock { (0x000 => CTLR: ReadWrite), (0x004 => TYPER: ReadOnly), (0x008 => _reserved1), (0x104 => ISENABLER: [ReadWrite; 31]), (0x180 => _reserved2), (0x820 => ITARGETSR: [ReadWrite; 248]), (0xC00 => @END), } } register_structs! { #[allow(non_snake_case)] BankedRegisterBlock { (0x000 => _reserved1), (0x100 => ISENABLER: ReadWrite), (0x104 => _reserved2), (0x800 => ITARGETSR: [ReadOnly; 8]), (0x820 => @END), } } ``` As with the implementation of the BCM interrupt controller driver, we won't cover the remaining parts in exhaustive detail. For that, please refer to [this folder] folder which contains all the sources. [this folder]: kernel/src/bsp/device_driver/arm ## Test it When you load the kernel, any keystroke results in echoing back the character by way of IRQ handling. There is no more polling done at the end of `kernel_main()`, just waiting for events such as IRQs: ```rust fn kernel_main() -> ! { // omitted for brevity info!("Echoing input now"); cpu::wait_forever(); } ``` Raspberry Pi 3: ```console $ make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 66 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.822492] mingo version 0.13.0 [ 0.822700] Booting on: Raspberry Pi 3 [ 0.823155] MMU online. Special regions: [ 0.823632] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data [ 0.824650] 0x3f000000 - 0x4000ffff | 17 MiB | Dev RW PXN | Device MMIO [ 0.825539] Current privilege level: EL1 [ 0.826015] Exception handling state: [ 0.826459] Debug: Masked [ 0.826849] SError: Masked [ 0.827239] IRQ: Unmasked [ 0.827651] FIQ: Masked [ 0.828041] Architectural timer resolution: 52 ns [ 0.828615] Drivers loaded: [ 0.828951] 1. BCM PL011 UART [ 0.829373] 2. BCM GPIO [ 0.829731] 3. BCM Interrupt Controller [ 0.830262] Registered IRQ handlers: [ 0.830695] Peripheral handler: [ 0.831141] 57. BCM PL011 UART [ 0.831649] Echoing input now ``` Raspberry Pi 4: ```console $ BSP=rpi4 make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 4 [ML] Requesting binary [MP] ⏩ Pushing 73 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.886853] mingo version 0.13.0 [ 0.886886] Booting on: Raspberry Pi 4 [ 0.887341] MMU online. Special regions: [ 0.887818] 0x00080000 - 0x0008ffff | 64 KiB | C RO PX | Kernel code and RO data [ 0.888836] 0xfe000000 - 0xff84ffff | 25 MiB | Dev RW PXN | Device MMIO [ 0.889725] Current privilege level: EL1 [ 0.890201] Exception handling state: [ 0.890645] Debug: Masked [ 0.891035] SError: Masked [ 0.891425] IRQ: Unmasked [ 0.891837] FIQ: Masked [ 0.892227] Architectural timer resolution: 18 ns [ 0.892801] Drivers loaded: [ 0.893137] 1. BCM PL011 UART [ 0.893560] 2. BCM GPIO [ 0.893917] 3. GICv2 (ARM Generic Interrupt Controller v2) [ 0.894654] Registered IRQ handlers: [ 0.895087] Peripheral handler: [ 0.895534] 153. BCM PL011 UART [ 0.896042] Echoing input now ``` ## Diff to previous ```diff diff -uNr 12_integrated_testing/kernel/Cargo.toml 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml --- 12_integrated_testing/kernel/Cargo.toml +++ 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.12.0" +version = "0.13.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 12_integrated_testing/kernel/src/_arch/aarch64/cpu/smp.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs --- 12_integrated_testing/kernel/src/_arch/aarch64/cpu/smp.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Architectural symmetric multiprocessing. +//! +//! # Orientation +//! +//! Since arch modules are imported into generic modules using the path attribute, the path of this +//! file is: +//! +//! crate::cpu::smp::arch_smp + +use aarch64_cpu::registers::*; +use tock_registers::interfaces::Readable; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return the executing core's id. +#[inline(always)] +pub fn core_id() -> T +where + T: From, +{ + const CORE_MASK: u64 = 0b11; + + T::from((MPIDR_EL1.get() & CORE_MASK) as u8) +} diff -uNr 12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs --- 12_integrated_testing/kernel/src/_arch/aarch64/exception/asynchronous.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs @@ -12,12 +12,17 @@ //! crate::exception::asynchronous::arch_asynchronous use aarch64_cpu::registers::*; -use tock_registers::interfaces::Readable; +use core::arch::asm; +use tock_registers::interfaces::{Readable, Writeable}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- +mod daif_bits { + pub const IRQ: u8 = 0b0010; +} + trait DaifField { fn daif_field() -> tock_registers::fields::Field; } @@ -66,6 +71,60 @@ // Public Code //-------------------------------------------------------------------------------------------------- +/// Returns whether IRQs are masked on the executing core. +pub fn is_local_irq_masked() -> bool { + !is_masked::() +} + +/// Unmask IRQs on the executing core. +/// +/// It is not needed to place an explicit instruction synchronization barrier after the `msr`. +/// Quoting the Architecture Reference Manual for ARMv8-A, section C5.1.3: +/// +/// "Writes to PSTATE.{PAN, D, A, I, F} occur in program order without the need for additional +/// synchronization." +#[inline(always)] +pub fn local_irq_unmask() { + unsafe { + asm!( + "msr DAIFClr, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core. +#[inline(always)] +pub fn local_irq_mask() { + unsafe { + asm!( + "msr DAIFSet, {arg}", + arg = const daif_bits::IRQ, + options(nomem, nostack, preserves_flags) + ); + } +} + +/// Mask IRQs on the executing core and return the previously saved interrupt mask bits (DAIF). +#[inline(always)] +pub fn local_irq_mask_save() -> u64 { + let saved = DAIF.get(); + local_irq_mask(); + + saved +} + +/// Restore the interrupt mask bits (DAIF) using the callee's argument. +/// +/// # Invariant +/// +/// - No sanity checks on the input. +#[inline(always)] +pub fn local_irq_restore(saved: u64) { + DAIF.set(saved); +} + /// Print the AArch64 exceptions status. #[rustfmt::skip] pub fn print_state() { diff -uNr 12_integrated_testing/kernel/src/_arch/aarch64/exception.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs --- 12_integrated_testing/kernel/src/_arch/aarch64/exception.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs @@ -11,6 +11,7 @@ //! //! crate::exception::arch_exception +use crate::exception; use aarch64_cpu::{asm::barrier, registers::*}; use core::{arch::global_asm, cell::UnsafeCell, fmt}; use tock_registers::{ @@ -102,8 +103,9 @@ } #[no_mangle] -extern "C" fn current_elx_irq(e: &mut ExceptionContext) { - default_exception_handler(e); +extern "C" fn current_elx_irq(_e: &mut ExceptionContext) { + let token = unsafe { &exception::asynchronous::IRQContext::new() }; + exception::asynchronous::irq_manager().handle_pending_irqs(token); } #[no_mangle] diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICC Driver - GIC CPU interface. + +use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::ReadWrite, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// CPU Interface Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Priority Mask Register + PMR [ + Priority OFFSET(0) NUMBITS(8) [] + ], + + /// Interrupt Acknowledge Register + IAR [ + InterruptID OFFSET(0) NUMBITS(10) [] + ], + + /// End of Interrupt Register + EOIR [ + EOIINTID OFFSET(0) NUMBITS(10) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + pub RegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => PMR: ReadWrite), + (0x008 => _reserved1), + (0x00C => IAR: ReadWrite), + (0x010 => EOIR: ReadWrite), + (0x014 => @END), + } +} + +/// Abstraction for the associated MMIO registers. +type Registers = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC CPU interface. +pub struct GICC { + registers: Registers, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + registers: Registers::new(mmio_start_addr), + } + } + + /// Accept interrupts of any priority. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field + /// value." + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn priority_accept_all(&self) { + self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. + } + + /// Enable the interface - start accepting IRQs. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + pub fn enable(&self) { + self.registers.CTLR.write(CTLR::Enable::SET); + } + + /// Extract the number of the highest-priority pending IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn pending_irq_number<'irq_context>( + &self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) -> usize { + self.registers.IAR.read(IAR::InterruptID) as usize + } + + /// Complete handling of the currently active IRQ. + /// + /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. + /// + /// To be called after `pending_irq_number()`. + /// + /// # Safety + /// + /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead + /// of `&mut self`. + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn mark_comleted<'irq_context>( + &self, + irq_number: u32, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); + } +} diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICD Driver - GIC Distributor. +//! +//! # Glossary +//! - SPI - Shared Peripheral Interrupt. + +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, state, synchronization, + synchronization::IRQSafeNullLock, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_bitfields, register_structs, + registers::{ReadOnly, ReadWrite}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_bitfields! { + u32, + + /// Distributor Control Register + CTLR [ + Enable OFFSET(0) NUMBITS(1) [] + ], + + /// Interrupt Controller Type Register + TYPER [ + ITLinesNumber OFFSET(0) NUMBITS(5) [] + ], + + /// Interrupt Processor Targets Registers + ITARGETSR [ + Offset3 OFFSET(24) NUMBITS(8) [], + Offset2 OFFSET(16) NUMBITS(8) [], + Offset1 OFFSET(8) NUMBITS(8) [], + Offset0 OFFSET(0) NUMBITS(8) [] + ] +} + +register_structs! { + #[allow(non_snake_case)] + SharedRegisterBlock { + (0x000 => CTLR: ReadWrite), + (0x004 => TYPER: ReadOnly), + (0x008 => _reserved1), + (0x104 => ISENABLER: [ReadWrite; 31]), + (0x180 => _reserved2), + (0x820 => ITARGETSR: [ReadWrite; 248]), + (0xC00 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + BankedRegisterBlock { + (0x000 => _reserved1), + (0x100 => ISENABLER: ReadWrite), + (0x104 => _reserved2), + (0x800 => ITARGETSR: [ReadOnly; 8]), + (0x820 => @END), + } +} + +/// Abstraction for the non-banked parts of the associated MMIO registers. +type SharedRegisters = MMIODerefWrapper; + +/// Abstraction for the banked parts of the associated MMIO registers. +type BankedRegisters = MMIODerefWrapper; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the GIC Distributor. +pub struct GICD { + /// Access to shared registers is guarded with a lock. + shared_registers: IRQSafeNullLock, + + /// Access to banked registers is unguarded. + banked_registers: BankedRegisters, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl SharedRegisters { + /// Return the number of IRQs that this HW implements. + #[inline(always)] + fn num_irqs(&mut self) -> usize { + // Query number of implemented IRQs. + // + // Refer to GICv2 Architecture Specification, Section 4.3.2. + ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 + } + + /// Return a slice of the implemented ITARGETSR. + #[inline(always)] + fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { + assert!(self.num_irqs() >= 36); + + // Calculate the max index of the shared ITARGETSR array. + // + // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS + // register has four entries, so shift right by two. Subtract one because we start + // counting at zero. + let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; + + // Rust automatically inserts slice range sanity check, i.e. max >= min. + &self.ITARGETSR[0..spi_itargetsr_max_index] + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::Mutex; + +impl GICD { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), + banked_registers: BankedRegisters::new(mmio_start_addr), + } + } + + /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. + /// + /// Quoting the GICv2 Architecture Specification: + /// + /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that + /// corresponds only to the processor reading the register." + fn local_gic_target_mask(&self) -> u32 { + self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) + } + + /// Route all SPIs to the boot core and enable the distributor. + pub fn boot_core_init(&self) { + assert!( + state::state_manager().is_init(), + "Only allowed during kernel init phase" + ); + + // Target all SPIs to the boot core only. + let mask = self.local_gic_target_mask(); + + self.shared_registers.lock(|regs| { + for i in regs.implemented_itargets_slice().iter() { + i.write( + ITARGETSR::Offset3.val(mask) + + ITARGETSR::Offset2.val(mask) + + ITARGETSR::Offset1.val(mask) + + ITARGETSR::Offset0.val(mask), + ); + } + + regs.CTLR.write(CTLR::Enable::SET); + }); + } + + /// Enable an interrupt. + pub fn enable(&self, irq_num: &super::IRQNumber) { + let irq_num = irq_num.get(); + + // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 + // (division by 32) and arrive at the index for the respective ISENABLER[i]. + let enable_reg_index = irq_num >> 5; + let enable_bit: u32 = 1u32 << (irq_num modulo 32); + + // Check if we are handling a private or shared IRQ. + match irq_num { + // Private. + 0..=31 => { + let enable_reg = &self.banked_registers.ISENABLER; + enable_reg.set(enable_reg.get() | enable_bit); + } + // Shared. + _ => { + let enable_reg_index_shared = enable_reg_index - 1; + + self.shared_registers.lock(|regs| { + let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; + enable_reg.set(enable_reg.get() | enable_bit); + }); + } + } + } +} diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/arm/gicv2.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! GICv2 Driver - ARM Generic Interrupt Controller v2. +//! +//! The following is a collection of excerpts with useful information from +//! - `Programmer's Guide for ARMv8-A` +//! - `ARM Generic Interrupt Controller Architecture Specification` +//! +//! # Programmer's Guide - 10.6.1 Configuration +//! +//! The GIC is accessed as a memory-mapped peripheral. +//! +//! All cores can access the common Distributor, but the CPU interface is banked, that is, each core +//! uses the same address to access its own private CPU interface. +//! +//! It is not possible for a core to access the CPU interface of another core. +//! +//! # Architecture Specification - 10.6.2 Initialization +//! +//! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized +//! after reset before it can deliver interrupts to the core. +//! +//! In the Distributor, software must configure the priority, target, security and enable individual +//! interrupts. The Distributor must subsequently be enabled through its control register +//! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption +//! settings. +//! +//! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This +//! prepares the GIC to deliver interrupts to the core. +//! +//! Before interrupts are expected in the core, software prepares the core to take interrupts by +//! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in +//! PSTATE, and setting the routing controls. +//! +//! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. +//! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. +//! Individual interrupts can also be disabled (or enabled) in the distributor. +//! +//! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must +//! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the +//! core's priority mask. +//! +//! # Architecture Specification - 1.4.2 Interrupt types +//! +//! - Peripheral interrupt +//! - Private Peripheral Interrupt (PPI) +//! - This is a peripheral interrupt that is specific to a single processor. +//! - Shared Peripheral Interrupt (SPI) +//! - This is a peripheral interrupt that the Distributor can route to any of a specified +//! combination of processors. +//! +//! - Software-generated interrupt (SGI) +//! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The +//! system uses SGIs for interprocessor communication. +//! - An SGI has edge-triggered properties. The software triggering of the interrupt is +//! equivalent to the edge transition of the interrupt request signal. +//! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt +//! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, +//! identifies the processor that requested the interrupt. +//! +//! # Architecture Specification - 2.2.1 Interrupt IDs +//! +//! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 +//! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by +//! the Distributor. +//! +//! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: +//! - Interrupt numbers 32..1019 are used for SPIs. +//! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These +//! interrupts are banked in the Distributor. +//! - A banked interrupt is one where the Distributor can have multiple interrupts with the +//! same ID. A banked interrupt is identified uniquely by its ID number and its associated +//! CPU interface number. Of the banked interrupt IDs: +//! - 00..15 SGIs +//! - 16..31 PPIs + +mod gicc; +mod gicd; + +use crate::{ + bsp::{self, device_driver::common::BoundedUsize}, + cpu, driver, exception, synchronization, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type HandlerTable = [Option>; + IRQNumber::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; + +/// Representation of the GIC. +pub struct GICv2 { + /// The Distributor. + gicd: gicd::GICD, + + /// The CPU Interface. + gicc: gicc::GICC, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl GICv2 { + const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. + + pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { + Self { + gicd: gicd::GICD::new(gicd_mmio_start_addr), + gicc: gicc::GICC::new(gicc_mmio_start_addr), + handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::ReadWriteEx; + +impl driver::interface::DeviceDriver for GICv2 { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } + + unsafe fn init(&self) -> Result<(), &'static str> { + if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { + self.gicd.boot_core_init(); + } + + self.gicc.priority_accept_all(); + self.gicc.enable(); + + Ok(()) + } +} + +impl exception::asynchronous::interface::IRQManager for GICv2 { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq_number: &Self::IRQNumberType) { + self.gicd.enable(irq_number); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register + // (IAR). + let irq_number = self.gicc.pending_irq_number(ic); + + // Guard against spurious interrupts. + if irq_number > GICv2::MAX_IRQ_NUMBER { + return; + } + + // Call the IRQ handler. Panic if there is none. + self.handler_table.read(|table| { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + }); + + // Signal completion of handling. + self.gicc.mark_comleted(irq_number as u32, ic); + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().skip(32).enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i + 32, handler.name()); + } + } + }); + } +} diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/arm.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/arm.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! ARM driver top level. + +pub mod gicv2; + +pub use gicv2::*; diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -5,8 +5,8 @@ //! GPIO Driver. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, - synchronization::NullLock, + bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, + synchronization, synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, @@ -118,7 +118,7 @@ /// Representation of the GPIO HW. pub struct GPIO { - inner: NullLock, + inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- @@ -200,7 +200,7 @@ /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { - inner: NullLock::new(GPIOInner::new(mmio_start_addr)), + inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), } } @@ -216,6 +216,8 @@ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { Self::COMPATIBLE } diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Peripheral Interrupt Controller Driver. +//! +//! # Resources +//! +//! - + +use super::{PendingIRQs, PeripheralIRQ}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, synchronization, + synchronization::{IRQSafeNullLock, InitStateLock}, +}; +use tock_registers::{ + interfaces::{Readable, Writeable}, + register_structs, + registers::{ReadOnly, WriteOnly}, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +register_structs! { + #[allow(non_snake_case)] + WORegisterBlock { + (0x00 => _reserved1), + (0x10 => ENABLE_1: WriteOnly), + (0x14 => ENABLE_2: WriteOnly), + (0x18 => @END), + } +} + +register_structs! { + #[allow(non_snake_case)] + RORegisterBlock { + (0x00 => _reserved1), + (0x04 => PENDING_1: ReadOnly), + (0x08 => PENDING_2: ReadOnly), + (0x0c => @END), + } +} + +/// Abstraction for the WriteOnly parts of the associated MMIO registers. +type WriteOnlyRegisters = MMIODerefWrapper; + +/// Abstraction for the ReadOnly parts of the associated MMIO registers. +type ReadOnlyRegisters = MMIODerefWrapper; + +type HandlerTable = [Option>; + PeripheralIRQ::MAX_INCLUSIVE + 1]; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Representation of the peripheral interrupt controller. +pub struct PeripheralIC { + /// Access to write registers is guarded with a lock. + wo_registers: IRQSafeNullLock, + + /// Register read access is unguarded. + ro_registers: ReadOnlyRegisters, + + /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. + handler_table: InitStateLock, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl PeripheralIC { + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(mmio_start_addr: usize) -> Self { + Self { + wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), + ro_registers: ReadOnlyRegisters::new(mmio_start_addr), + handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), + } + } + + /// Query the list of pending IRQs. + fn pending_irqs(&self) -> PendingIRQs { + let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) + | u64::from(self.ro_registers.PENDING_1.get()); + + PendingIRQs::new(pending_mask) + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ +use synchronization::interface::{Mutex, ReadWriteEx}; + +impl exception::asynchronous::interface::IRQManager for PeripheralIC { + type IRQNumberType = PeripheralIRQ; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + self.handler_table.write(|table| { + let irq_number = irq_handler_descriptor.number().get(); + + if table[irq_number].is_some() { + return Err("IRQ handler already registered"); + } + + table[irq_number] = Some(irq_handler_descriptor); + + Ok(()) + }) + } + + fn enable(&self, irq: &Self::IRQNumberType) { + self.wo_registers.lock(|regs| { + let enable_reg = if irq.get() <= 31 { + ®s.ENABLE_1 + } else { + ®s.ENABLE_2 + }; + + let enable_bit: u32 = 1 << (irq.get() modulo 32); + + // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable + // bits are unaffected. So we don't need read and OR'ing here. + enable_reg.set(enable_bit); + }); + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + _ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + self.handler_table.read(|table| { + for irq_number in self.pending_irqs() { + match table[irq_number] { + None => panic!("No handler registered for IRQ {}", irq_number), + Some(descriptor) => { + // Call the IRQ handler. Panics on failure. + descriptor.handler().handle().expect("Error handling IRQ"); + } + } + } + }) + } + + fn print_handler(&self) { + use crate::info; + + info!(" Peripheral handler:"); + + self.handler_table.read(|table| { + for (i, opt) in table.iter().enumerate() { + if let Some(handler) = opt { + info!(" {: >3}. {}", i, handler.name()); + } + } + }); + } +} diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Interrupt Controller Driver. + +mod peripheral_ic; + +use crate::{ + bsp::device_driver::common::BoundedUsize, + driver, + exception::{self, asynchronous::IRQHandlerDescriptor}, +}; +use core::fmt; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Wrapper struct for a bitmask indicating pending IRQ numbers. +struct PendingIRQs { + bitmask: u64, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; +pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; + +/// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. +#[derive(Copy, Clone)] +#[allow(missing_docs)] +pub enum IRQNumber { + Local(LocalIRQ), + Peripheral(PeripheralIRQ), +} + +/// Representation of the Interrupt Controller. +pub struct InterruptController { + periph: peripheral_ic::PeripheralIC, +} + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl PendingIRQs { + pub fn new(bitmask: u64) -> Self { + Self { bitmask } + } +} + +impl Iterator for PendingIRQs { + type Item = usize; + + fn next(&mut self) -> Option { + if self.bitmask == 0 { + return None; + } + + let next = self.bitmask.trailing_zeros() as usize; + self.bitmask &= self.bitmask.wrapping_sub(1); + Some(next) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl fmt::Display for IRQNumber { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Local(number) => write!(f, "Local({})", number), + Self::Peripheral(number) => write!(f, "Peripheral({})", number), + } + } +} + +impl InterruptController { + // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. + const MAX_LOCAL_IRQ_NUMBER: usize = 3; + const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; + + pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; + + /// Create an instance. + /// + /// # Safety + /// + /// - The user must ensure to provide a correct MMIO start address. + pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { + Self { + periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), + } + } +} + +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl driver::interface::DeviceDriver for InterruptController { + type IRQNumberType = IRQNumber; + + fn compatible(&self) -> &'static str { + Self::COMPATIBLE + } +} + +impl exception::asynchronous::interface::IRQManager for InterruptController { + type IRQNumberType = IRQNumber; + + fn register_handler( + &self, + irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + match irq_handler_descriptor.number() { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => { + let periph_descriptor = IRQHandlerDescriptor::new( + pirq, + irq_handler_descriptor.name(), + irq_handler_descriptor.handler(), + ); + + self.periph.register_handler(periph_descriptor) + } + } + } + + fn enable(&self, irq: &Self::IRQNumberType) { + match irq { + IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), + IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), + } + } + + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &exception::asynchronous::IRQContext<'irq_context>, + ) { + // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. + self.periph.handle_pending_irqs(ic) + } + + fn print_handler(&self) { + self.periph.print_handler(); + } +} diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -10,8 +10,11 @@ //! - use crate::{ - bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, - synchronization::NullLock, + bsp::device_driver::common::MMIODerefWrapper, + console, cpu, driver, + exception::{self, asynchronous::IRQNumber}, + synchronization, + synchronization::IRQSafeNullLock, }; use core::fmt; use tock_registers::{ @@ -134,6 +137,52 @@ ] ], + /// Interrupt FIFO Level Select Register. + IFLS [ + /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as + /// follows. + RXIFLSEL OFFSET(3) NUMBITS(5) [ + OneEigth = 0b000, + OneQuarter = 0b001, + OneHalf = 0b010, + ThreeQuarters = 0b011, + SevenEights = 0b100 + ] + ], + + /// Interrupt Mask Set/Clear Register. + IMSC [ + /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR + /// interrupt. + /// + /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. + /// - A write of 0 clears the mask. + RTIM OFFSET(6) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ], + + /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. + /// + /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. + /// - A write of 0 clears the mask. + RXIM OFFSET(4) NUMBITS(1) [ + Disabled = 0, + Enabled = 1 + ] + ], + + /// Masked Interrupt Status Register. + MIS [ + /// Receive timeout masked interrupt status. Returns the masked interrupt state of the + /// UARTRTINTR interrupt. + RTMIS OFFSET(6) NUMBITS(1) [], + + /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR + /// interrupt. + RXMIS OFFSET(4) NUMBITS(1) [] + ], + /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. @@ -152,7 +201,10 @@ (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), - (0x34 => _reserved3), + (0x34 => IFLS: ReadWrite), + (0x38 => IMSC: ReadWrite), + (0x3C => _reserved3), + (0x40 => MIS: ReadOnly), (0x44 => ICR: WriteOnly), (0x48 => @END), } @@ -179,7 +231,7 @@ /// Representation of the UART. pub struct PL011Uart { - inner: NullLock, + inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- @@ -247,6 +299,14 @@ .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); + // Set RX FIFO fill level at 1/8. + self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); + + // Enable RX IRQ + RX timeout IRQ. + self.registers + .IMSC + .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); + // Turn the UART on. self.registers .CR @@ -337,7 +397,7 @@ /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { - inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), + inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } } } @@ -348,6 +408,8 @@ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { + type IRQNumberType = IRQNumber; + fn compatible(&self) -> &'static str { Self::COMPATIBLE } @@ -357,6 +419,20 @@ Ok(()) } + + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; + + let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); + + irq_manager().register_handler(descriptor)?; + irq_manager().enable(irq_number); + + Ok(()) + } } impl console::interface::Write for PL011Uart { @@ -405,3 +481,24 @@ } impl console::interface::All for PL011Uart {} + +impl exception::asynchronous::interface::IRQHandler for PL011Uart { + fn handle(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| { + let pending = inner.registers.MIS.extract(); + + // Clear all pending IRQs. + inner.registers.ICR.write(ICR::ALL::CLEAR); + + // Check for any kind of RX interrupt. + if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { + // Echo any received characters. + while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { + inner.write_char(c) + } + } + }); + + Ok(()) + } +} diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/bcm.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs @@ -5,7 +5,11 @@ //! BCM driver top level. mod bcm2xxx_gpio; +#[cfg(feature = "bsp_rpi3")] +mod bcm2xxx_interrupt_controller; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; +#[cfg(feature = "bsp_rpi3")] +pub use bcm2xxx_interrupt_controller::*; pub use bcm2xxx_pl011_uart::*; diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver/common.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs --- 12_integrated_testing/kernel/src/bsp/device_driver/common.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs @@ -4,7 +4,7 @@ //! Common device driver code. -use core::{marker::PhantomData, ops}; +use core::{fmt, marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -15,6 +15,10 @@ phantom: PhantomData T>, } +/// A wrapper type for usize with integrated range bound check. +#[derive(Copy, Clone)] +pub struct BoundedUsize(usize); + //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -36,3 +40,25 @@ unsafe { &*(self.start_addr as *const _) } } } + +impl BoundedUsize<{ MAX_INCLUSIVE }> { + pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; + + /// Creates a new instance if number <= MAX_INCLUSIVE. + pub const fn new(number: usize) -> Self { + assert!(number <= MAX_INCLUSIVE); + + Self(number) + } + + /// Return the wrapped number. + pub const fn get(self) -> usize { + self.0 + } +} + +impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff -uNr 12_integrated_testing/kernel/src/bsp/device_driver.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs --- 12_integrated_testing/kernel/src/bsp/device_driver.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs @@ -4,9 +4,13 @@ //! Device driver. +#[cfg(feature = "bsp_rpi4")] +mod arm; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; +#[cfg(feature = "bsp_rpi4")] +pub use arm::*; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs --- 12_integrated_testing/kernel/src/bsp/raspberrypi/driver.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs @@ -4,8 +4,12 @@ //! BSP driver support. -use super::memory::map::mmio; -use crate::{bsp::device_driver, console, driver as generic_driver}; +use super::{exception, memory::map::mmio}; +use crate::{ + bsp::device_driver, + console, driver as generic_driver, + exception::{self as generic_exception}, +}; use core::sync::atomic::{AtomicBool, Ordering}; //-------------------------------------------------------------------------------------------------- @@ -16,6 +20,14 @@ unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; +#[cfg(feature = "bsp_rpi3")] +static INTERRUPT_CONTROLLER: device_driver::InterruptController = + unsafe { device_driver::InterruptController::new(mmio::PERIPHERAL_IC_START) }; + +#[cfg(feature = "bsp_rpi4")] +static INTERRUPT_CONTROLLER: device_driver::GICv2 = + unsafe { device_driver::GICv2::new(mmio::GICD_START, mmio::GICC_START) }; + //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- @@ -33,21 +45,43 @@ Ok(()) } +/// This must be called only after successful init of the interrupt controller driver. +fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(&INTERRUPT_CONTROLLER); + + Ok(()) +} + fn driver_uart() -> Result<(), &'static str> { - let uart_descriptor = - generic_driver::DeviceDriverDescriptor::new(&PL011_UART, Some(post_init_uart)); + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( + &PL011_UART, + Some(post_init_uart), + Some(exception::asynchronous::irq_map::PL011_UART), + ); generic_driver::driver_manager().register_driver(uart_descriptor); Ok(()) } fn driver_gpio() -> Result<(), &'static str> { - let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio)); + let gpio_descriptor = + generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio), None); generic_driver::driver_manager().register_driver(gpio_descriptor); Ok(()) } +fn driver_interrupt_controller() -> Result<(), &'static str> { + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( + &INTERRUPT_CONTROLLER, + Some(post_init_interrupt_controller), + None, + ); + generic_driver::driver_manager().register_driver(interrupt_controller_descriptor); + + Ok(()) +} + //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -65,6 +99,7 @@ driver_uart()?; driver_gpio()?; + driver_interrupt_controller()?; INIT_DONE.store(true, Ordering::Relaxed); Ok(()) diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs --- 12_integrated_testing/kernel/src/bsp/raspberrypi/exception/asynchronous.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP asynchronous exception handling. + +use crate::bsp; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Export for reuse in generic asynchronous.rs. +pub use bsp::device_driver::IRQNumber; + +#[cfg(feature = "bsp_rpi3")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::{IRQNumber, PeripheralIRQ}; + + pub const PL011_UART: IRQNumber = IRQNumber::Peripheral(PeripheralIRQ::new(57)); +} + +#[cfg(feature = "bsp_rpi4")] +pub(in crate::bsp) mod irq_map { + use super::bsp::device_driver::IRQNumber; + + pub const PL011_UART: IRQNumber = IRQNumber::new(153); +} diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/exception.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs --- 12_integrated_testing/kernel/src/bsp/raspberrypi/exception.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs @@ -0,0 +1,7 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! BSP synchronous and asynchronous exception handling. + +pub mod asynchronous; diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs --- 12_integrated_testing/kernel/src/bsp/raspberrypi/memory.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs @@ -73,10 +73,11 @@ pub mod mmio { use super::*; - pub const START: usize = 0x3F00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0x4000_FFFF; + pub const START: usize = 0x3F00_0000; + pub const PERIPHERAL_IC_START: usize = START + 0x0000_B200; + pub const GPIO_START: usize = START + GPIO_OFFSET; + pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const END_INCLUSIVE: usize = 0x4000_FFFF; } /// Physical devices. @@ -87,6 +88,8 @@ pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; + pub const GICD_START: usize = 0xFF84_1000; + pub const GICC_START: usize = 0xFF84_2000; pub const END_INCLUSIVE: usize = 0xFF84_FFFF; } } diff -uNr 12_integrated_testing/kernel/src/bsp/raspberrypi.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs --- 12_integrated_testing/kernel/src/bsp/raspberrypi.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs @@ -6,6 +6,7 @@ pub mod cpu; pub mod driver; +pub mod exception; pub mod memory; //-------------------------------------------------------------------------------------------------- diff -uNr 12_integrated_testing/kernel/src/console.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs --- 12_integrated_testing/kernel/src/console.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs @@ -6,7 +6,7 @@ mod null_console; -use crate::synchronization::{self, NullLock}; +use crate::synchronization; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -60,22 +60,22 @@ // Global instances //-------------------------------------------------------------------------------------------------- -static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = - NullLock::new(&null_console::NULL_CONSOLE); +static CUR_CONSOLE: InitStateLock<&'static (dyn interface::All + Sync)> = + InitStateLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -use synchronization::interface::Mutex; +use synchronization::{interface::ReadWriteEx, InitStateLock}; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { - CUR_CONSOLE.lock(|con| *con = new_console); + CUR_CONSOLE.write(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { - CUR_CONSOLE.lock(|con| *con) + CUR_CONSOLE.read(|con| *con) } diff -uNr 12_integrated_testing/kernel/src/cpu/smp.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs --- 12_integrated_testing/kernel/src/cpu/smp.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2018-2023 Andre Richter + +//! Symmetric multiprocessing. + +#[cfg(target_arch = "aarch64")] +#[path = "../_arch/aarch64/cpu/smp.rs"] +mod arch_smp; + +//-------------------------------------------------------------------------------------------------- +// Architectural Public Reexports +//-------------------------------------------------------------------------------------------------- +pub use arch_smp::core_id; diff -uNr 12_integrated_testing/kernel/src/cpu.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs --- 12_integrated_testing/kernel/src/cpu.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs @@ -10,6 +10,8 @@ mod boot; +pub mod smp; + //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- diff -uNr 12_integrated_testing/kernel/src/driver.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs --- 12_integrated_testing/kernel/src/driver.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs @@ -5,9 +5,10 @@ //! Driver support. use crate::{ - info, - synchronization::{interface::Mutex, NullLock}, + exception, info, + synchronization::{interface::ReadWriteEx, InitStateLock}, }; +use core::fmt; //-------------------------------------------------------------------------------------------------- // Private Definitions @@ -15,9 +16,12 @@ const NUM_DRIVERS: usize = 5; -struct DriverManagerInner { +struct DriverManagerInner +where + T: 'static, +{ next_index: usize, - descriptors: [Option; NUM_DRIVERS], + descriptors: [Option>; NUM_DRIVERS], } //-------------------------------------------------------------------------------------------------- @@ -28,6 +32,9 @@ pub mod interface { /// Device Driver functions. pub trait DeviceDriver { + /// Different interrupt controllers might use different types for IRQ number. + type IRQNumberType: super::fmt::Display; + /// Return a compatibility string for identifying the driver. fn compatible(&self) -> &'static str; @@ -39,6 +46,21 @@ unsafe fn init(&self) -> Result<(), &'static str> { Ok(()) } + + /// Called by the kernel to register and enable the device's IRQ handler. + /// + /// Rust's type system will prevent a call to this function unless the calling instance + /// itself has static lifetime. + fn register_and_enable_irq_handler( + &'static self, + irq_number: &Self::IRQNumberType, + ) -> Result<(), &'static str> { + panic!( + "Attempt to enable IRQ {} for device {}, but driver does not support this", + irq_number, + self.compatible() + ) + } } } @@ -47,27 +69,37 @@ /// A descriptor for device drivers. #[derive(Copy, Clone)] -pub struct DeviceDriverDescriptor { - device_driver: &'static (dyn interface::DeviceDriver + Sync), +pub struct DeviceDriverDescriptor +where + T: 'static, +{ + device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, + irq_number: Option, } /// Provides device driver management functions. -pub struct DriverManager { - inner: NullLock, +pub struct DriverManager +where + T: 'static, +{ + inner: InitStateLock>, } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- -static DRIVER_MANAGER: DriverManager = DriverManager::new(); +static DRIVER_MANAGER: DriverManager = DriverManager::new(); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -impl DriverManagerInner { +impl DriverManagerInner +where + T: 'static + Copy, +{ /// Create an instance. pub const fn new() -> Self { Self { @@ -81,43 +113,48 @@ // Public Code //-------------------------------------------------------------------------------------------------- -impl DeviceDriverDescriptor { +impl DeviceDriverDescriptor { /// Create an instance. pub fn new( - device_driver: &'static (dyn interface::DeviceDriver + Sync), + device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, + irq_number: Option, ) -> Self { Self { device_driver, post_init_callback, + irq_number, } } } /// Return a reference to the global DriverManager. -pub fn driver_manager() -> &'static DriverManager { +pub fn driver_manager() -> &'static DriverManager { &DRIVER_MANAGER } -impl DriverManager { +impl DriverManager +where + T: fmt::Display + Copy, +{ /// Create an instance. pub const fn new() -> Self { Self { - inner: NullLock::new(DriverManagerInner::new()), + inner: InitStateLock::new(DriverManagerInner::new()), } } /// Register a device driver with the kernel. - pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { - self.inner.lock(|inner| { + pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { + self.inner.write(|inner| { inner.descriptors[inner.next_index] = Some(descriptor); inner.next_index += 1; }) } /// Helper for iterating over registered drivers. - fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { - self.inner.lock(|inner| { + fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { + self.inner.read(|inner| { inner .descriptors .iter() @@ -126,12 +163,12 @@ }) } - /// Fully initialize all drivers. + /// Fully initialize all drivers and their interrupts handlers. /// /// # Safety /// /// - During init, drivers might do stuff with system-wide impact. - pub unsafe fn init_drivers(&self) { + pub unsafe fn init_drivers_and_irqs(&self) { self.for_each_descriptor(|descriptor| { // 1. Initialize driver. if let Err(x) = descriptor.device_driver.init() { @@ -150,6 +187,23 @@ descriptor.device_driver.compatible(), x ); + } + } + }); + + // 3. After all post-init callbacks were done, the interrupt controller should be + // registered and functional. So let drivers register with it now. + self.for_each_descriptor(|descriptor| { + if let Some(irq_number) = &descriptor.irq_number { + if let Err(x) = descriptor + .device_driver + .register_and_enable_irq_handler(irq_number) + { + panic!( + "Error during driver interrupt handler registration: {}: {}", + descriptor.device_driver.compatible(), + x + ); } } }); diff -uNr 12_integrated_testing/kernel/src/exception/asynchronous/null_irq_manager.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs --- 12_integrated_testing/kernel/src/exception/asynchronous/null_irq_manager.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2022-2023 Andre Richter + +//! Null IRQ Manager. + +use super::{interface, IRQContext, IRQHandlerDescriptor}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +pub struct NullIRQManager; + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +pub static NULL_IRQ_MANAGER: NullIRQManager = NullIRQManager {}; + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl interface::IRQManager for NullIRQManager { + type IRQNumberType = super::IRQNumber; + + fn register_handler( + &self, + _descriptor: IRQHandlerDescriptor, + ) -> Result<(), &'static str> { + panic!("No IRQ Manager registered yet"); + } + + fn enable(&self, _irq_number: &Self::IRQNumberType) { + panic!("No IRQ Manager registered yet"); + } + + fn handle_pending_irqs<'irq_context>(&'irq_context self, _ic: &IRQContext<'irq_context>) { + panic!("No IRQ Manager registered yet"); + } +} diff -uNr 12_integrated_testing/kernel/src/exception/asynchronous.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs --- 12_integrated_testing/kernel/src/exception/asynchronous.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs @@ -7,8 +7,184 @@ #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/exception/asynchronous.rs"] mod arch_asynchronous; +mod null_irq_manager; + +use crate::{bsp, synchronization}; +use core::marker::PhantomData; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- -pub use arch_asynchronous::print_state; +pub use arch_asynchronous::{ + is_local_irq_masked, local_irq_mask, local_irq_mask_save, local_irq_restore, local_irq_unmask, + print_state, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Interrupt number as defined by the BSP. +pub type IRQNumber = bsp::exception::asynchronous::IRQNumber; + +/// Interrupt descriptor. +#[derive(Copy, Clone)] +pub struct IRQHandlerDescriptor +where + T: Copy, +{ + /// The IRQ number. + number: T, + + /// Descriptive name. + name: &'static str, + + /// Reference to handler trait object. + handler: &'static (dyn interface::IRQHandler + Sync), +} + +/// IRQContext token. +/// +/// An instance of this type indicates that the local core is currently executing in IRQ +/// context, aka executing an interrupt vector or subcalls of it. +/// +/// Concept and implementation derived from the `CriticalSection` introduced in +/// +#[derive(Clone, Copy)] +pub struct IRQContext<'irq_context> { + _0: PhantomData<&'irq_context ()>, +} + +/// Asynchronous exception handling interfaces. +pub mod interface { + + /// Implemented by types that handle IRQs. + pub trait IRQHandler { + /// Called when the corresponding interrupt is asserted. + fn handle(&self) -> Result<(), &'static str>; + } + + /// IRQ management functions. + /// + /// The `BSP` is supposed to supply one global instance. Typically implemented by the + /// platform's interrupt controller. + pub trait IRQManager { + /// The IRQ number type depends on the implementation. + type IRQNumberType: Copy; + + /// Register a handler. + fn register_handler( + &self, + irq_handler_descriptor: super::IRQHandlerDescriptor, + ) -> Result<(), &'static str>; + + /// Enable an interrupt in the controller. + fn enable(&self, irq_number: &Self::IRQNumberType); + + /// Handle pending interrupts. + /// + /// This function is called directly from the CPU's IRQ exception vector. On AArch64, + /// this means that the respective CPU core has disabled exception handling. + /// This function can therefore not be preempted and runs start to finish. + /// + /// Takes an IRQContext token to ensure it can only be called from IRQ context. + #[allow(clippy::trivially_copy_pass_by_ref)] + fn handle_pending_irqs<'irq_context>( + &'irq_context self, + ic: &super::IRQContext<'irq_context>, + ); + + /// Print list of registered handlers. + fn print_handler(&self) {} + } +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static CUR_IRQ_MANAGER: InitStateLock< + &'static (dyn interface::IRQManager + Sync), +> = InitStateLock::new(&null_irq_manager::NULL_IRQ_MANAGER); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::{interface::ReadWriteEx, InitStateLock}; + +impl IRQHandlerDescriptor +where + T: Copy, +{ + /// Create an instance. + pub const fn new( + number: T, + name: &'static str, + handler: &'static (dyn interface::IRQHandler + Sync), + ) -> Self { + Self { + number, + name, + handler, + } + } + + /// Return the number. + pub const fn number(&self) -> T { + self.number + } + + /// Return the name. + pub const fn name(&self) -> &'static str { + self.name + } + + /// Return the handler. + pub const fn handler(&self) -> &'static (dyn interface::IRQHandler + Sync) { + self.handler + } +} + +impl<'irq_context> IRQContext<'irq_context> { + /// Creates an IRQContext token. + /// + /// # Safety + /// + /// - This must only be called when the current core is in an interrupt context and will not + /// live beyond the end of it. That is, creation is allowed in interrupt vector functions. For + /// example, in the ARMv8-A case, in `extern "C" fn current_elx_irq()`. + /// - Note that the lifetime `'irq_context` of the returned instance is unconstrained. User code + /// must not be able to influence the lifetime picked for this type, since that might cause it + /// to be inferred to `'static`. + #[inline(always)] + pub unsafe fn new() -> Self { + IRQContext { _0: PhantomData } + } +} + +/// Executes the provided closure while IRQs are masked on the executing core. +/// +/// While the function temporarily changes the HW state of the executing core, it restores it to the +/// previous state before returning, so this is deemed safe. +#[inline(always)] +pub fn exec_with_irq_masked(f: impl FnOnce() -> T) -> T { + let saved = local_irq_mask_save(); + let ret = f(); + local_irq_restore(saved); + + ret +} + +/// Register a new IRQ manager. +pub fn register_irq_manager( + new_manager: &'static (dyn interface::IRQManager + Sync), +) { + CUR_IRQ_MANAGER.write(|manager| *manager = new_manager); +} + +/// Return a reference to the currently registered IRQ manager. +/// +/// This is the IRQ manager used by the architectural interrupt handling code. +pub fn irq_manager() -> &'static dyn interface::IRQManager { + CUR_IRQ_MANAGER.read(|manager| *manager) +} diff -uNr 12_integrated_testing/kernel/src/lib.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs --- 12_integrated_testing/kernel/src/lib.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs @@ -138,6 +138,7 @@ pub mod exception; pub mod memory; pub mod print; +pub mod state; pub mod time; //-------------------------------------------------------------------------------------------------- diff -uNr 12_integrated_testing/kernel/src/main.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs --- 12_integrated_testing/kernel/src/main.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs @@ -13,7 +13,7 @@ #![no_main] #![no_std] -use libkernel::{bsp, console, driver, exception, info, memory, time}; +use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; /// Early init code. /// @@ -23,7 +23,7 @@ /// - The init calls in this function must appear in the correct order: /// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, /// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ -/// NullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. +/// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; @@ -40,8 +40,13 @@ } // Initialize all device drivers. - driver::driver_manager().init_drivers(); - // println! is usable from here on. + driver::driver_manager().init_drivers_and_irqs(); + + // Unmask interrupts on the boot CPU core. + exception::asynchronous::local_irq_unmask(); + + // Announce conclusion of the kernel_init() phase. + state::state_manager().transition_to_single_core_main(); // Transition from unsafe to safe. kernel_main() @@ -49,8 +54,6 @@ /// The main function running after the early init. fn kernel_main() -> ! { - use console::console; - info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); @@ -71,12 +74,9 @@ info!("Drivers loaded:"); driver::driver_manager().enumerate(); - info!("Echoing input now"); + info!("Registered IRQ handlers:"); + exception::asynchronous::irq_manager().print_handler(); - // Discard any spurious received characters before going into echo mode. - console().clear_rx(); - loop { - let c = console().read_char(); - console().write_char(c); - } + info!("Echoing input now"); + cpu::wait_forever(); } diff -uNr 12_integrated_testing/kernel/src/panic_wait.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs --- 12_integrated_testing/kernel/src/panic_wait.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs @@ -4,7 +4,7 @@ //! A panic handler that infinitely waits. -use crate::{cpu, println}; +use crate::{cpu, exception, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- @@ -59,6 +59,8 @@ #[panic_handler] fn panic(info: &PanicInfo) -> ! { + exception::asynchronous::local_irq_mask(); + // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); diff -uNr 12_integrated_testing/kernel/src/state.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs --- 12_integrated_testing/kernel/src/state.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! State information about the kernel itself. + +use core::sync::atomic::{AtomicU8, Ordering}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Different stages in the kernel execution. +#[derive(Copy, Clone, Eq, PartialEq)] +enum State { + /// The kernel starts booting in this state. + Init, + + /// The kernel transitions to this state when jumping to `kernel_main()` (at the end of + /// `kernel_init()`, after all init calls are done). + SingleCoreMain, + + /// The kernel transitions to this state when it boots the secondary cores, aka switches + /// exectution mode to symmetric multiprocessing (SMP). + MultiCoreMain, +} + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Maintains the kernel state and state transitions. +pub struct StateManager(AtomicU8); + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static STATE_MANAGER: StateManager = StateManager::new(); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the global StateManager. +pub fn state_manager() -> &'static StateManager { + &STATE_MANAGER +} + +impl StateManager { + const INIT: u8 = 0; + const SINGLE_CORE_MAIN: u8 = 1; + const MULTI_CORE_MAIN: u8 = 2; + + /// Create a new instance. + pub const fn new() -> Self { + Self(AtomicU8::new(Self::INIT)) + } + + /// Return the current state. + fn state(&self) -> State { + let state = self.0.load(Ordering::Acquire); + + match state { + Self::INIT => State::Init, + Self::SINGLE_CORE_MAIN => State::SingleCoreMain, + Self::MULTI_CORE_MAIN => State::MultiCoreMain, + _ => panic!("Invalid KERNEL_STATE"), + } + } + + /// Return if the kernel is init state. + pub fn is_init(&self) -> bool { + self.state() == State::Init + } + + /// Transition from Init to SingleCoreMain. + pub fn transition_to_single_core_main(&self) { + if self + .0 + .compare_exchange( + Self::INIT, + Self::SINGLE_CORE_MAIN, + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_err() + { + panic!("transition_to_single_core_main() called while state != Init"); + } + } +} diff -uNr 12_integrated_testing/kernel/src/synchronization.rs 13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs --- 12_integrated_testing/kernel/src/synchronization.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs @@ -28,6 +28,21 @@ /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } + + /// A reader-writer exclusion type. + /// + /// The implementing object allows either a number of readers or at most one writer at any point + /// in time. + pub trait ReadWriteEx { + /// The type of encapsulated data. + type Data; + + /// Grants temporary mutable access to the encapsulated data. + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; + + /// Grants temporary immutable access to the encapsulated data. + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R; + } } /// A pseudo-lock for teaching purposes. @@ -36,8 +51,18 @@ /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is -/// executing single-threaded, aka only running on a single core with interrupts disabled. -pub struct NullLock +/// executing on a single core. +pub struct IRQSafeNullLock +where + T: ?Sized, +{ + data: UnsafeCell, +} + +/// A pseudo-lock that is RW during the single-core kernel init phase and RO afterwards. +/// +/// Intended to encapsulate data that is populated during kernel init when no concurrency exists. +pub struct InitStateLock where T: ?Sized, { @@ -48,10 +73,22 @@ // Public Code //-------------------------------------------------------------------------------------------------- -unsafe impl Send for NullLock where T: ?Sized + Send {} -unsafe impl Sync for NullLock where T: ?Sized + Send {} +unsafe impl Send for IRQSafeNullLock where T: ?Sized + Send {} +unsafe impl Sync for IRQSafeNullLock where T: ?Sized + Send {} + +impl IRQSafeNullLock { + /// Create an instance. + pub const fn new(data: T) -> Self { + Self { + data: UnsafeCell::new(data), + } + } +} + +unsafe impl Send for InitStateLock where T: ?Sized + Send {} +unsafe impl Sync for InitStateLock where T: ?Sized + Send {} -impl NullLock { +impl InitStateLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { @@ -63,8 +100,9 @@ //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ +use crate::{exception, state}; -impl interface::Mutex for NullLock { +impl interface::Mutex for IRQSafeNullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { @@ -72,6 +110,50 @@ // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; + // Execute the closure while IRQs are masked. + exception::asynchronous::exec_with_irq_masked(|| f(data)) + } +} + +impl interface::ReadWriteEx for InitStateLock { + type Data = T; + + fn write<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { + assert!( + state::state_manager().is_init(), + "InitStateLock::write called after kernel init phase" + ); + assert!( + !exception::asynchronous::is_local_irq_masked(), + "InitStateLock::write called with IRQs unmasked" + ); + + let data = unsafe { &mut *self.data.get() }; + f(data) } + + fn read<'a, R>(&'a self, f: impl FnOnce(&'a Self::Data) -> R) -> R { + let data = unsafe { &*self.data.get() }; + + f(data) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// InitStateLock must be transparent. + #[kernel_test] + fn init_state_lock_is_transparent() { + use core::mem::size_of; + + assert_eq!(size_of::>(), size_of::()); + } } diff -uNr 12_integrated_testing/kernel/tests/04_exception_irq_sanity.rs 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs --- 12_integrated_testing/kernel/tests/04_exception_irq_sanity.rs +++ 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! IRQ handling sanity tests. + +#![feature(custom_test_frameworks)] +#![no_main] +#![no_std] +#![reexport_test_harness_main = "test_main"] +#![test_runner(libkernel::test_runner)] + +use libkernel::{bsp, cpu, exception}; +use test_macros::kernel_test; + +#[no_mangle] +unsafe fn kernel_init() -> ! { + bsp::driver::qemu_bring_up_console(); + + exception::handling_init(); + exception::asynchronous::local_irq_unmask(); + + test_main(); + + cpu::qemu_exit_success() +} + +/// Check that IRQ masking works. +#[kernel_test] +fn local_irq_mask_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + // Restore earlier state. + exception::asynchronous::local_irq_unmask(); +} + +/// Check that IRQ unmasking works. +#[kernel_test] +fn local_irq_unmask_works() { + // Precondition: IRQs are masked. + exception::asynchronous::local_irq_mask(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + exception::asynchronous::local_irq_unmask(); + assert!(exception::asynchronous::is_local_irq_masked()); +} + +/// Check that IRQ mask save is saving "something". +#[kernel_test] +fn local_irq_mask_save_works() { + // Precondition: IRQs are unmasked. + assert!(exception::asynchronous::is_local_irq_masked()); + + let first = exception::asynchronous::local_irq_mask_save(); + assert!(!exception::asynchronous::is_local_irq_masked()); + + let second = exception::asynchronous::local_irq_mask_save(); + assert_ne!(first, second); + + exception::asynchronous::local_irq_restore(first); + assert!(exception::asynchronous::is_local_irq_masked()); +} ``` ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/build.rs ================================================ 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())); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prepares the transition from EL2 to EL1. /// /// # Safety /// /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. /// /// # Safety /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. x0 holds the function argument provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::translation_table::arch_translation_table use crate::{ bsp, memory, memory::mmu::{ arch_mmu::{Granule512MiB, Granule64KiB}, AccessPermissions, AttributeFields, MemAttributes, }, }; use core::convert; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, registers::InMemoryRegister, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. register_bitfields! {u64, STAGE1_TABLE_DESCRIPTOR [ /// Physical address of the next descriptor. NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] TYPE OFFSET(1) NUMBITS(1) [ Block = 0, Table = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } // A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. register_bitfields! {u64, STAGE1_PAGE_DESCRIPTOR [ /// Unprivileged execute-never. UXN OFFSET(54) NUMBITS(1) [ False = 0, True = 1 ], /// Privileged execute-never. PXN OFFSET(53) NUMBITS(1) [ False = 0, True = 1 ], /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] /// Access flag. AF OFFSET(10) NUMBITS(1) [ False = 0, True = 1 ], /// Shareability field. SH OFFSET(8) NUMBITS(2) [ OuterShareable = 0b10, InnerShareable = 0b11 ], /// Access Permissions. AP OFFSET(6) NUMBITS(2) [ RW_EL1 = 0b00, RW_EL1_EL0 = 0b01, RO_EL1 = 0b10, RO_EL1_EL0 = 0b11 ], /// Memory attributes index into the MAIR_EL1 register. AttrIndx OFFSET(2) NUMBITS(3) [], TYPE OFFSET(1) NUMBITS(1) [ Reserved_Invalid = 0, Page = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } /// A table descriptor for 64 KiB aperture. /// /// The output points to the next table. #[derive(Copy, Clone)] #[repr(C)] struct TableDescriptor { value: u64, } /// A page descriptor with 64 KiB aperture. /// /// The output points to physical memory. #[derive(Copy, Clone)] #[repr(C)] struct PageDescriptor { value: u64, } trait StartAddr { fn phys_start_addr_u64(&self) -> u64; fn phys_start_addr_usize(&self) -> usize; } const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB /// aligned, so the lvl3 is put first. #[repr(C)] #[repr(align(65536))] pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], } /// A translation table type for the kernel space. pub type KernelTranslationTable = FixedSizeTranslationTable; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- // The binary is still identity mapped, so we don't need to convert here. impl StartAddr for [T; N] { fn phys_start_addr_u64(&self) -> u64 { self as *const T as u64 } fn phys_start_addr_usize(&self) -> usize { self as *const _ as usize } } impl TableDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance pointing to the supplied address. pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; val.write( STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + STAGE1_TABLE_DESCRIPTOR::VALID::True, ); TableDescriptor { value: val.get() } } } /// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. impl convert::From for tock_registers::fields::FieldValue { fn from(attribute_fields: AttributeFields) -> Self { // Memory attributes. let mut desc = match attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => { STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) } MemAttributes::Device => { STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) } }; // Access Permissions. desc += match attribute_fields.acc_perms { AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, }; // The execute-never attribute is mapped to PXN in AArch64. desc += if attribute_fields.execute_never { STAGE1_PAGE_DESCRIPTOR::PXN::True } else { STAGE1_PAGE_DESCRIPTOR::PXN::False }; // Always set unprivileged exectue-never as long as userspace is not implemented yet. desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; desc } } impl PageDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance. pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; val.write( STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + STAGE1_PAGE_DESCRIPTOR::AF::True + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + STAGE1_PAGE_DESCRIPTOR::VALID::True + (*attribute_fields).into(), ); Self { value: val.get() } } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl FixedSizeTranslationTable { /// Create an instance. pub const fn new() -> Self { // Can't have a zero-sized address space. assert!(NUM_TABLES > 0); Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], } } /// Iterates over all static translation table entries and fills them at once. /// /// # Safety /// /// - Modifies a `static mut`. Ensure it only happens from here. pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { *l2_entry = TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); let (phys_output_addr, attribute_fields) = bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); } } Ok(()) } /// The translation table's base address to be used for programming the MMU. pub fn phys_base_address(&self) -> u64 { self.lvl2.phys_start_addr_u64() } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Check if the size of `struct TableDescriptor` is as expected. #[kernel_test] fn size_of_tabledescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } /// Check if the size of `struct PageDescriptor` is as expected. #[kernel_test] fn size_of_pagedescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::arch_mmu use crate::{ bsp, memory, memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, }; use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Memory Management Unit type. struct MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; /// Constants for indexing the MAIR_EL1. #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. /// /// # Safety /// /// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); static MMU: MemoryManagementUnit = MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AddressSpace { /// Checks for architectural restrictions. pub const fn arch_address_space_size_sanity_checks() { // Size must be at least one full 512 MiB table. assert!((AS_SIZE % Granule512MiB::SIZE) == 0); // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 // version. assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } /// Configure various settings of stage 1 of the EL1 translation regime. fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the MMU instance. pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use memory::mmu::MMUEnableError; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } // Fail early if translation granule is not supported. if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } // Prepare the memory attribute indirection register. self.set_up_mair(); // Populate translation tables. KERNEL_TABLES .populate_tt_entries() .map_err(MMUEnableError::Other)?; // Set the "Translation Table Base Register". TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); self.configure_translation_control(); // Switch the MMU on. // // First, force all previous changes to be seen before the MMU is enabled. barrier::isb(barrier::SY); // Enable the MMU and turn on data and instruction caching. SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); // Force MMU init to complete before next instruction. barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use core::{cell::UnsafeCell, ops::Range}; use test_macros::kernel_test; /// Check if KERNEL_TABLES is in .bss. #[kernel_test] fn kernel_tables_in_bss() { extern "Rust" { static __bss_start: UnsafeCell; static __bss_end_exclusive: UnsafeCell; } let bss_range = unsafe { Range { start: __bss_start.get(), end: __bss_end_exclusive.get(), } }; let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; assert!(bss_range.contains(&kernel_tables_addr)); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! GICC Driver - GIC CPU interface. use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- register_bitfields! { u32, /// CPU Interface Control Register CTLR [ Enable OFFSET(0) NUMBITS(1) [] ], /// Interrupt Priority Mask Register PMR [ Priority OFFSET(0) NUMBITS(8) [] ], /// Interrupt Acknowledge Register IAR [ InterruptID OFFSET(0) NUMBITS(10) [] ], /// End of Interrupt Register EOIR [ EOIINTID OFFSET(0) NUMBITS(10) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x000 => CTLR: ReadWrite), (0x004 => PMR: ReadWrite), (0x008 => _reserved1), (0x00C => IAR: ReadWrite), (0x010 => EOIR: ReadWrite), (0x014 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GIC CPU interface. pub struct GICC { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GICC { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Accept interrupts of any priority. /// /// Quoting the GICv2 Architecture Specification: /// /// "Writing 255 to the GICC_PMR always sets it to the largest supported priority field /// value." /// /// # Safety /// /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead /// of `&mut self`. pub fn priority_accept_all(&self) { self.registers.PMR.write(PMR::Priority.val(255)); // Comment in arch spec. } /// Enable the interface - start accepting IRQs. /// /// # Safety /// /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead /// of `&mut self`. pub fn enable(&self) { self.registers.CTLR.write(CTLR::Enable::SET); } /// Extract the number of the highest-priority pending IRQ. /// /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. /// /// # Safety /// /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead /// of `&mut self`. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn pending_irq_number<'irq_context>( &self, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) -> usize { self.registers.IAR.read(IAR::InterruptID) as usize } /// Complete handling of the currently active IRQ. /// /// Can only be called from IRQ context, which is ensured by taking an `IRQContext` token. /// /// To be called after `pending_irq_number()`. /// /// # Safety /// /// - GICC MMIO registers are banked per CPU core. It is therefore safe to have `&self` instead /// of `&mut self`. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn mark_comleted<'irq_context>( &self, irq_number: u32, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) { self.registers.EOIR.write(EOIR::EOIINTID.val(irq_number)); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! GICD Driver - GIC Distributor. //! //! # Glossary //! - SPI - Shared Peripheral Interrupt. use crate::{ bsp::device_driver::common::MMIODerefWrapper, state, synchronization, synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- register_bitfields! { u32, /// Distributor Control Register CTLR [ Enable OFFSET(0) NUMBITS(1) [] ], /// Interrupt Controller Type Register TYPER [ ITLinesNumber OFFSET(0) NUMBITS(5) [] ], /// Interrupt Processor Targets Registers ITARGETSR [ Offset3 OFFSET(24) NUMBITS(8) [], Offset2 OFFSET(16) NUMBITS(8) [], Offset1 OFFSET(8) NUMBITS(8) [], Offset0 OFFSET(0) NUMBITS(8) [] ] } register_structs! { #[allow(non_snake_case)] SharedRegisterBlock { (0x000 => CTLR: ReadWrite), (0x004 => TYPER: ReadOnly), (0x008 => _reserved1), (0x104 => ISENABLER: [ReadWrite; 31]), (0x180 => _reserved2), (0x820 => ITARGETSR: [ReadWrite; 248]), (0xC00 => @END), } } register_structs! { #[allow(non_snake_case)] BankedRegisterBlock { (0x000 => _reserved1), (0x100 => ISENABLER: ReadWrite), (0x104 => _reserved2), (0x800 => ITARGETSR: [ReadOnly; 8]), (0x820 => @END), } } /// Abstraction for the non-banked parts of the associated MMIO registers. type SharedRegisters = MMIODerefWrapper; /// Abstraction for the banked parts of the associated MMIO registers. type BankedRegisters = MMIODerefWrapper; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GIC Distributor. pub struct GICD { /// Access to shared registers is guarded with a lock. shared_registers: IRQSafeNullLock, /// Access to banked registers is unguarded. banked_registers: BankedRegisters, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl SharedRegisters { /// Return the number of IRQs that this HW implements. #[inline(always)] fn num_irqs(&mut self) -> usize { // Query number of implemented IRQs. // // Refer to GICv2 Architecture Specification, Section 4.3.2. ((self.TYPER.read(TYPER::ITLinesNumber) as usize) + 1) * 32 } /// Return a slice of the implemented ITARGETSR. #[inline(always)] fn implemented_itargets_slice(&mut self) -> &[ReadWrite] { assert!(self.num_irqs() >= 36); // Calculate the max index of the shared ITARGETSR array. // // The first 32 IRQs are private, so not included in `shared_registers`. Each ITARGETS // register has four entries, so shift right by two. Subtract one because we start // counting at zero. let spi_itargetsr_max_index = ((self.num_irqs() - 32) >> 2) - 1; // Rust automatically inserts slice range sanity check, i.e. max >= min. &self.ITARGETSR[0..spi_itargetsr_max_index] } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; impl GICD { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), banked_registers: BankedRegisters::new(mmio_start_addr), } } /// Use a banked ITARGETSR to retrieve the executing core's GIC target mask. /// /// Quoting the GICv2 Architecture Specification: /// /// "GICD_ITARGETSR0 to GICD_ITARGETSR7 are read-only, and each field returns a value that /// corresponds only to the processor reading the register." fn local_gic_target_mask(&self) -> u32 { self.banked_registers.ITARGETSR[0].read(ITARGETSR::Offset0) } /// Route all SPIs to the boot core and enable the distributor. pub fn boot_core_init(&self) { assert!( state::state_manager().is_init(), "Only allowed during kernel init phase" ); // Target all SPIs to the boot core only. let mask = self.local_gic_target_mask(); self.shared_registers.lock(|regs| { for i in regs.implemented_itargets_slice().iter() { i.write( ITARGETSR::Offset3.val(mask) + ITARGETSR::Offset2.val(mask) + ITARGETSR::Offset1.val(mask) + ITARGETSR::Offset0.val(mask), ); } regs.CTLR.write(CTLR::Enable::SET); }); } /// Enable an interrupt. pub fn enable(&self, irq_num: &super::IRQNumber) { let irq_num = irq_num.get(); // Each bit in the u32 enable register corresponds to one IRQ number. Shift right by 5 // (division by 32) and arrive at the index for the respective ISENABLER[i]. let enable_reg_index = irq_num >> 5; let enable_bit: u32 = 1u32 << (irq_num % 32); // Check if we are handling a private or shared IRQ. match irq_num { // Private. 0..=31 => { let enable_reg = &self.banked_registers.ISENABLER; enable_reg.set(enable_reg.get() | enable_bit); } // Shared. _ => { let enable_reg_index_shared = enable_reg_index - 1; self.shared_registers.lock(|regs| { let enable_reg = ®s.ISENABLER[enable_reg_index_shared]; enable_reg.set(enable_reg.get() | enable_bit); }); } } } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! GICv2 Driver - ARM Generic Interrupt Controller v2. //! //! The following is a collection of excerpts with useful information from //! - `Programmer's Guide for ARMv8-A` //! - `ARM Generic Interrupt Controller Architecture Specification` //! //! # Programmer's Guide - 10.6.1 Configuration //! //! The GIC is accessed as a memory-mapped peripheral. //! //! All cores can access the common Distributor, but the CPU interface is banked, that is, each core //! uses the same address to access its own private CPU interface. //! //! It is not possible for a core to access the CPU interface of another core. //! //! # Architecture Specification - 10.6.2 Initialization //! //! Both the Distributor and the CPU interfaces are disabled at reset. The GIC must be initialized //! after reset before it can deliver interrupts to the core. //! //! In the Distributor, software must configure the priority, target, security and enable individual //! interrupts. The Distributor must subsequently be enabled through its control register //! (GICD_CTLR). For each CPU interface, software must program the priority mask and preemption //! settings. //! //! Each CPU interface block itself must be enabled through its control register (GICD_CTLR). This //! prepares the GIC to deliver interrupts to the core. //! //! Before interrupts are expected in the core, software prepares the core to take interrupts by //! setting a valid interrupt vector in the vector table, and clearing interrupt mask bits in //! PSTATE, and setting the routing controls. //! //! The entire interrupt mechanism in the system can be disabled by disabling the Distributor. //! Interrupt delivery to an individual core can be disabled by disabling its CPU interface. //! Individual interrupts can also be disabled (or enabled) in the distributor. //! //! For an interrupt to reach the core, the individual interrupt, Distributor and CPU interface must //! all be enabled. The interrupt also needs to be of sufficient priority, that is, higher than the //! core's priority mask. //! //! # Architecture Specification - 1.4.2 Interrupt types //! //! - Peripheral interrupt //! - Private Peripheral Interrupt (PPI) //! - This is a peripheral interrupt that is specific to a single processor. //! - Shared Peripheral Interrupt (SPI) //! - This is a peripheral interrupt that the Distributor can route to any of a specified //! combination of processors. //! //! - Software-generated interrupt (SGI) //! - This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The //! system uses SGIs for interprocessor communication. //! - An SGI has edge-triggered properties. The software triggering of the interrupt is //! equivalent to the edge transition of the interrupt request signal. //! - When an SGI occurs in a multiprocessor implementation, the CPUID field in the Interrupt //! Acknowledge Register, GICC_IAR, or the Aliased Interrupt Acknowledge Register, GICC_AIAR, //! identifies the processor that requested the interrupt. //! //! # Architecture Specification - 2.2.1 Interrupt IDs //! //! Interrupts from sources are identified using ID numbers. Each CPU interface can see up to 1020 //! interrupts. The banking of SPIs and PPIs increases the total number of interrupts supported by //! the Distributor. //! //! The GIC assigns interrupt ID numbers ID0-ID1019 as follows: //! - Interrupt numbers 32..1019 are used for SPIs. //! - Interrupt numbers 0..31 are used for interrupts that are private to a CPU interface. These //! interrupts are banked in the Distributor. //! - A banked interrupt is one where the Distributor can have multiple interrupts with the //! same ID. A banked interrupt is identified uniquely by its ID number and its associated //! CPU interface number. Of the banked interrupt IDs: //! - 00..15 SGIs //! - 16..31 PPIs mod gicc; mod gicd; use crate::{ bsp::{self, device_driver::common::BoundedUsize}, cpu, driver, exception, synchronization, synchronization::InitStateLock, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- type HandlerTable = [Option>; IRQNumber::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. pub type IRQNumber = BoundedUsize<{ GICv2::MAX_IRQ_NUMBER }>; /// Representation of the GIC. pub struct GICv2 { /// The Distributor. gicd: gicd::GICD, /// The CPU Interface. gicc: gicc::GICC, /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. handler_table: InitStateLock, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GICv2 { const MAX_IRQ_NUMBER: usize = 300; // Normally 1019, but keep it lower to save some space. pub const COMPATIBLE: &'static str = "GICv2 (ARM Generic Interrupt Controller v2)"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { Self { gicd: gicd::GICD::new(gicd_mmio_start_addr), gicc: gicc::GICC::new(gicc_mmio_start_addr), handler_table: InitStateLock::new([None; IRQNumber::MAX_INCLUSIVE + 1]), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::ReadWriteEx; impl driver::interface::DeviceDriver for GICv2 { type IRQNumberType = IRQNumber; fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { if bsp::cpu::BOOT_CORE_ID == cpu::smp::core_id() { self.gicd.boot_core_init(); } self.gicc.priority_accept_all(); self.gicc.enable(); Ok(()) } } impl exception::asynchronous::interface::IRQManager for GICv2 { type IRQNumberType = IRQNumber; fn register_handler( &self, irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } fn enable(&self, irq_number: &Self::IRQNumberType) { self.gicd.enable(irq_number); } fn handle_pending_irqs<'irq_context>( &'irq_context self, ic: &exception::asynchronous::IRQContext<'irq_context>, ) { // Extract the highest priority pending IRQ number from the Interrupt Acknowledge Register // (IAR). let irq_number = self.gicc.pending_irq_number(ic); // Guard against spurious interrupts. if irq_number > GICv2::MAX_IRQ_NUMBER { return; } // Call the IRQ handler. Panic if there is none. self.handler_table.read(|table| { match table[irq_number] { None => panic!("No handler registered for IRQ {}", irq_number), Some(descriptor) => { // Call the IRQ handler. Panics on failure. descriptor.handler().handle().expect("Error handling IRQ"); } } }); // Signal completion of handling. self.gicc.mark_comleted(irq_number as u32, ic); } fn print_handler(&self) { use crate::info; info!(" Peripheral handler:"); self.handler_table.read(|table| { for (i, opt) in table.iter().skip(32).enumerate() { if let Some(handler) = opt { info!(" {: >3}. {}", i + 32, handler.name()); } } }); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, synchronization, synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { type IRQNumberType = IRQNumber; fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Peripheral Interrupt Controller Driver. //! //! # Resources //! //! - use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, exception, synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; use tock_registers::{ interfaces::{Readable, Writeable}, register_structs, registers::{ReadOnly, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- register_structs! { #[allow(non_snake_case)] WORegisterBlock { (0x00 => _reserved1), (0x10 => ENABLE_1: WriteOnly), (0x14 => ENABLE_2: WriteOnly), (0x18 => @END), } } register_structs! { #[allow(non_snake_case)] RORegisterBlock { (0x00 => _reserved1), (0x04 => PENDING_1: ReadOnly), (0x08 => PENDING_2: ReadOnly), (0x0c => @END), } } /// Abstraction for the WriteOnly parts of the associated MMIO registers. type WriteOnlyRegisters = MMIODerefWrapper; /// Abstraction for the ReadOnly parts of the associated MMIO registers. type ReadOnlyRegisters = MMIODerefWrapper; type HandlerTable = [Option>; PeripheralIRQ::MAX_INCLUSIVE + 1]; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the peripheral interrupt controller. pub struct PeripheralIC { /// Access to write registers is guarded with a lock. wo_registers: IRQSafeNullLock, /// Register read access is unguarded. ro_registers: ReadOnlyRegisters, /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. handler_table: InitStateLock, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PeripheralIC { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), ro_registers: ReadOnlyRegisters::new(mmio_start_addr), handler_table: InitStateLock::new([None; PeripheralIRQ::MAX_INCLUSIVE + 1]), } } /// Query the list of pending IRQs. fn pending_irqs(&self) -> PendingIRQs { let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) | u64::from(self.ro_registers.PENDING_1.get()); PendingIRQs::new(pending_mask) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::{Mutex, ReadWriteEx}; impl exception::asynchronous::interface::IRQManager for PeripheralIC { type IRQNumberType = PeripheralIRQ; fn register_handler( &self, irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } fn enable(&self, irq: &Self::IRQNumberType) { self.wo_registers.lock(|regs| { let enable_reg = if irq.get() <= 31 { ®s.ENABLE_1 } else { ®s.ENABLE_2 }; let enable_bit: u32 = 1 << (irq.get() % 32); // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable // bits are unaffected. So we don't need read and OR'ing here. enable_reg.set(enable_bit); }); } fn handle_pending_irqs<'irq_context>( &'irq_context self, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) { self.handler_table.read(|table| { for irq_number in self.pending_irqs() { match table[irq_number] { None => panic!("No handler registered for IRQ {}", irq_number), Some(descriptor) => { // Call the IRQ handler. Panics on failure. descriptor.handler().handle().expect("Error handling IRQ"); } } } }) } fn print_handler(&self) { use crate::info; info!(" Peripheral handler:"); self.handler_table.read(|table| { for (i, opt) in table.iter().enumerate() { if let Some(handler) = opt { info!(" {: >3}. {}", i, handler.name()); } } }); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Interrupt Controller Driver. mod peripheral_ic; use crate::{ bsp::device_driver::common::BoundedUsize, driver, exception::{self, asynchronous::IRQHandlerDescriptor}, }; use core::fmt; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Wrapper struct for a bitmask indicating pending IRQ numbers. struct PendingIRQs { bitmask: u64, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub type LocalIRQ = BoundedUsize<{ InterruptController::MAX_LOCAL_IRQ_NUMBER }>; pub type PeripheralIRQ = BoundedUsize<{ InterruptController::MAX_PERIPHERAL_IRQ_NUMBER }>; /// Used for the associated type of trait [`exception::asynchronous::interface::IRQManager`]. #[derive(Copy, Clone)] #[allow(missing_docs)] pub enum IRQNumber { Local(LocalIRQ), Peripheral(PeripheralIRQ), } /// Representation of the Interrupt Controller. pub struct InterruptController { periph: peripheral_ic::PeripheralIC, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PendingIRQs { pub fn new(bitmask: u64) -> Self { Self { bitmask } } } impl Iterator for PendingIRQs { type Item = usize; fn next(&mut self) -> Option { if self.bitmask == 0 { return None; } let next = self.bitmask.trailing_zeros() as usize; self.bitmask &= self.bitmask.wrapping_sub(1); Some(next) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl fmt::Display for IRQNumber { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Local(number) => write!(f, "Local({})", number), Self::Peripheral(number) => write!(f, "Peripheral({})", number), } } } impl InterruptController { // Restrict to 3 for now. This makes future code for local_ic.rs more straight forward. const MAX_LOCAL_IRQ_NUMBER: usize = 3; const MAX_PERIPHERAL_IRQ_NUMBER: usize = 63; pub const COMPATIBLE: &'static str = "BCM Interrupt Controller"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { Self { periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl driver::interface::DeviceDriver for InterruptController { type IRQNumberType = IRQNumber; fn compatible(&self) -> &'static str { Self::COMPATIBLE } } impl exception::asynchronous::interface::IRQManager for InterruptController { type IRQNumberType = IRQNumber; fn register_handler( &self, irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { match irq_handler_descriptor.number() { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), IRQNumber::Peripheral(pirq) => { let periph_descriptor = IRQHandlerDescriptor::new( pirq, irq_handler_descriptor.name(), irq_handler_descriptor.handler(), ); self.periph.register_handler(periph_descriptor) } } } fn enable(&self, irq: &Self::IRQNumberType) { match irq { IRQNumber::Local(_) => unimplemented!("Local IRQ controller not implemented."), IRQNumber::Peripheral(pirq) => self.periph.enable(pirq), } } fn handle_pending_irqs<'irq_context>( &'irq_context self, ic: &exception::asynchronous::IRQContext<'irq_context>, ) { // It can only be a peripheral IRQ pending because enable() does not support local IRQs yet. self.periph.handle_pending_irqs(ic) } fn print_handler(&self) { self.periph.print_handler(); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception::{self, asynchronous::IRQNumber}, synchronization, synchronization::IRQSafeNullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt FIFO Level Select Register. IFLS [ /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as /// follows. RXIFLSEL OFFSET(3) NUMBITS(5) [ OneEigth = 0b000, OneQuarter = 0b001, OneHalf = 0b010, ThreeQuarters = 0b011, SevenEights = 0b100 ] ], /// Interrupt Mask Set/Clear Register. IMSC [ /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR /// interrupt. /// /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. /// - A write of 0 clears the mask. RTIM OFFSET(6) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. /// /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. /// - A write of 0 clears the mask. RXIM OFFSET(4) NUMBITS(1) [ Disabled = 0, Enabled = 1 ] ], /// Masked Interrupt Status Register. MIS [ /// Receive timeout masked interrupt status. Returns the masked interrupt state of the /// UARTRTINTR interrupt. RTMIS OFFSET(6) NUMBITS(1) [], /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR /// interrupt. RXMIS OFFSET(4) NUMBITS(1) [] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => IFLS: ReadWrite), (0x38 => IMSC: ReadWrite), (0x3C => _reserved3), (0x40 => MIS: ReadOnly), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Set RX FIFO fill level at 1/8. self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); // Enable RX IRQ + RX timeout IRQ. self.registers .IMSC .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { type IRQNumberType = IRQNumber; fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } fn register_and_enable_irq_handler( &'static self, irq_number: &Self::IRQNumberType, ) -> Result<(), &'static str> { use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); irq_manager().register_handler(descriptor)?; irq_manager().enable(irq_number); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { let pending = inner.registers.MIS.extract(); // Clear all pending IRQs. inner.registers.ICR.write(ICR::ALL::CLEAR); // Check for any kind of RX interrupt. if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { // Echo any received characters. while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { inner.write_char(c) } } }); Ok(()) } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{fmt, marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } /// A wrapper type for usize with integrated range bound check. #[derive(Copy, Clone)] pub struct BoundedUsize(usize); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } impl BoundedUsize<{ MAX_INCLUSIVE }> { pub const MAX_INCLUSIVE: usize = MAX_INCLUSIVE; /// Creates a new instance if number <= MAX_INCLUSIVE. pub const fn new(number: usize) -> Self { assert!(number <= MAX_INCLUSIVE); Self(number) } /// Return the wrapped number. pub const fn get(self) -> usize { self.0 } } impl fmt::Display for BoundedUsize<{ MAX_INCLUSIVE }> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW * * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. * It doesn't mean all of them need actually be loaded. */ PHDRS { segment_boot_core_stack PT_LOAD FLAGS(6); segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); } SECTIONS { . = __rpi_phys_dram_start_addr; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : { /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __code_start = .; .text : { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ *(.text._start_rust) /* The Rust entry point */ *(.text*) /* Everything else */ } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { __bss_start = .; *(.bss*); . = ALIGN(16); __bss_end_exclusive = .; } :segment_data /*********************************************************************************************** * Misc ***********************************************************************************************/ .got : { *(.got*) } ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") /DISCARD/ : { *(.comment*) } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. use super::map as memory_map; use crate::memory::mmu::*; use core::ops::RangeInclusive; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The kernel's address space defined by this BSP. pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; const NUM_MEM_RANGES: usize = 2; /// The virtual memory layout. /// /// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. /// It is agnostic of the paging granularity that the architecture's MMU will use. pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( memory_map::END_INCLUSIVE, [ TranslationDescriptor { name: "Kernel code and RO data", virtual_range: code_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadOnly, execute_never: false, }, }, TranslationDescriptor { name: "Device MMIO", virtual_range: mmio_range_inclusive, physical_range_translation: Translation::Identity, attribute_fields: AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, }, ], ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- fn code_range_inclusive() -> RangeInclusive { // Notice the subtraction to turn the exclusive end into an inclusive end. #[allow(clippy::range_minus_one)] RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) } fn mmio_range_inclusive() -> RangeInclusive { RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the virtual memory layout. pub fn virt_mem_layout() -> &'static KernelVirtualLayout { &LAYOUT } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Check alignment of the kernel's virtual memory layout sections. #[kernel_test] fn virt_mem_layout_sections_are_64KiB_aligned() { const SIXTYFOUR_KIB: usize = 65536; for i in LAYOUT.inner().iter() { let start: usize = *(i.virtual_range)().start(); let end: usize = *(i.virtual_range)().end() + 1; assert_eq!(start % SIXTYFOUR_KIB, 0); assert_eq!(end % SIXTYFOUR_KIB, 0); assert!(end >= start); } } /// Ensure the kernel's virtual memory layout is free of overlaps. #[kernel_test] fn virt_mem_layout_has_no_overlaps() { let layout = virt_mem_layout().inner(); for (i, first) in layout.iter().enumerate() { for second in layout.iter().skip(i + 1) { let first_range = first.virtual_range; let second_range = second.virtual_range; assert!(!first_range().contains(second_range().start())); assert!(!first_range().contains(second_range().end())); assert!(!second_range().contains(first_range().start())); assert!(!second_range().contains(first_range().end())); } } } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! //! The physical memory layout. //! //! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used //! as the boot core's stack. //! //! +---------------------------------------+ //! | | 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | //! | | pub mod mmu; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // Symbols from the linker script. extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { /// The inclusive end address of the memory map. /// /// End address + 1 must be power of two. /// /// # Note /// /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. /// /// However, making this trade-off has the downside of making it possible for the CPU to assert a /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const PERIPHERAL_IC_START: usize = START + 0x0000_B200; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const END_INCLUSIVE: usize = 0x4000_FFFF; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; pub const GICD_START: usize = 0xFF84_1000; pub const GICC_START: usize = 0xFF84_2000; pub const END_INCLUSIVE: usize = 0xFF84_FFFF; } } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Start page address of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_start() -> usize { unsafe { __code_start.get() as usize } } /// Exclusive end page address of the code segment. /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_end_exclusive() -> usize { unsafe { __code_end_exclusive.get() as usize } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` library. //! //! Used to compose the final kernel binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![allow(incomplete_features)] #![feature(asm_const)] #![feature(const_option)] #![feature(core_intrinsics)] #![feature(format_args_nl)] #![feature(int_roundings)] #![feature(linkage)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_std] // Testing #![cfg_attr(test, no_main)] #![feature(custom_test_frameworks)] #![reexport_test_harness_main = "test_main"] #![test_runner(crate::test_runner)] mod panic_wait; mod synchronization; pub mod bsp; pub mod common; pub mod console; pub mod cpu; pub mod driver; pub mod exception; pub mod memory; pub mod print; pub mod state; pub mod time; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Version string. pub fn version() -> &'static str { concat!( env!("CARGO_PKG_NAME"), " version ", env!("CARGO_PKG_VERSION") ) } #[cfg(not(test))] extern "Rust" { fn kernel_init() -> !; } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- /// The default runner for unit tests. pub fn test_runner(tests: &[&test_types::UnitTest]) { // This line will be printed as the test header. println!("Running {} tests", tests.len()); for (i, test) in tests.iter().enumerate() { print!("{:>3}. {:.<58}", i + 1, test.name); // Run the actual test. (test.test_func)(); // Failed tests call panic!(). Execution reaches here only if the test has passed. println!("[ok]") } } /// The `kernel_init()` for unit tests. #[cfg(test)] #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); bsp::driver::qemu_bring_up_console(); test_main(); cpu::qemu_exit_success() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. #![feature(format_args_nl)] #![no_main] #![no_std] use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order: /// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, /// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ /// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { panic!("MMU: {}", string); } // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers_and_irqs(); // Unmask interrupts on the boot CPU core. exception::asynchronous::local_irq_unmask(); // Announce conclusion of the kernel_init() phase. state::state_manager().transition_to_single_core_main(); // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); info!("MMU online. Special regions:"); bsp::memory::mmu::virt_mem_layout().print_layout(); let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); info!("Exception handling state:"); exception::asynchronous::print_state(); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); info!("Registered IRQ handlers:"); exception::asynchronous::irq_manager().print_handler(); info!("Echoing input now"); cpu::wait_forever(); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Translation table. #[cfg(target_arch = "aarch64")] #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] mod arch_translation_table; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_translation_table::KernelTranslationTable; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. //! //! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file //! provides types for composing an architecture-agnostic description of the kernel's virtual memory //! layout. //! //! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` //! function. //! //! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and //! install respective translation tables. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; mod translation_table; use crate::common; use core::{fmt, ops::RangeInclusive}; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_mmu::mmu; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// MMU enable errors variants. #[allow(missing_docs)] #[derive(Debug)] pub enum MMUEnableError { AlreadyEnabled, Other(&'static str), } /// Memory Management interfaces. pub mod interface { use super::*; /// MMU functions. pub trait MMU { /// Called by the kernel during early init. Supposed to take the translation tables from the /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. /// /// # Safety /// /// - Changes the HW's global state. unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; } } /// Describes the characteristics of a translation granule. pub struct TranslationGranule; /// Describes properties of an address space. pub struct AddressSpace; /// Architecture agnostic translation types. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum Translation { Identity, Offset(usize), } /// Architecture agnostic memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum MemAttributes { CacheableDRAM, Device, } /// Architecture agnostic access permissions. #[allow(missing_docs)] #[derive(Copy, Clone)] pub enum AccessPermissions { ReadOnly, ReadWrite, } /// Collection of memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, pub execute_never: bool, } /// Architecture agnostic descriptor for a memory range. #[allow(missing_docs)] pub struct TranslationDescriptor { pub name: &'static str, pub virtual_range: fn() -> RangeInclusive, pub physical_range_translation: Translation, pub attribute_fields: AttributeFields, } /// Type for expressing the kernel's virtual memory layout. pub struct KernelVirtualLayout { /// The last (inclusive) address of the address space. max_virt_addr_inclusive: usize, /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl fmt::Display for MMUEnableError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), MMUEnableError::Other(x) => write!(f, "{}", x), } } } impl TranslationGranule { /// The granule's size. pub const SIZE: usize = Self::size_checked(); /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(GRANULE_SIZE.is_power_of_two()); GRANULE_SIZE } } impl AddressSpace { /// The address space size. pub const SIZE: usize = Self::size_checked(); /// The address space shift, aka log2(size). pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(AS_SIZE.is_power_of_two()); // Check for architectural restrictions as well. Self::arch_address_space_size_sanity_checks(); AS_SIZE } } impl Default for AttributeFields { fn default() -> AttributeFields { AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, } } } /// Human-readable output of a TranslationDescriptor. impl fmt::Display for TranslationDescriptor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Call the function to which self.range points, and dereference the result, which causes // Rust to copy the value. let start = *(self.virtual_range)().start(); let end = *(self.virtual_range)().end(); let size = end - start + 1; let (size, unit) = common::size_human_readable_ceil(size); let attr = match self.attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => "C", MemAttributes::Device => "Dev", }; let acc_p = match self.attribute_fields.acc_perms { AccessPermissions::ReadOnly => "RO", AccessPermissions::ReadWrite => "RW", }; let xn = if self.attribute_fields.execute_never { "PXN" } else { "PX" }; write!( f, " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", start, end, size, unit, attr, acc_p, xn, self.name ) } } impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { /// Create a new instance. pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { Self { max_virt_addr_inclusive: max, inner: layout, } } /// For a virtual address, find and return the physical output address and corresponding /// attributes. /// /// If the address is not found in `inner`, return an identity mapped default with normal /// cacheable DRAM attributes. pub fn virt_addr_properties( &self, virt_addr: usize, ) -> Result<(usize, AttributeFields), &'static str> { if virt_addr > self.max_virt_addr_inclusive { return Err("Address out of range"); } for i in self.inner.iter() { if (i.virtual_range)().contains(&virt_addr) { let output_addr = match i.physical_range_translation { Translation::Identity => virt_addr, Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), }; return Ok((output_addr, i.attribute_fields)); } } Ok((virt_addr, AttributeFields::default())) } /// Print the memory layout. pub fn print_layout(&self) { use crate::info; for i in self.inner.iter() { info!("{}", i); } } #[cfg(test)] pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { &self.inner } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management. pub mod mmu; ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Console sanity tests - RX, TX and statistics. #![feature(format_args_nl)] #![no_main] #![no_std] /// Console tests should time out on the I/O harness in case of panic. mod panic_wait_forever; use libkernel::{bsp, console, cpu, exception, print}; #[no_mangle] unsafe fn kernel_init() -> ! { use console::console; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // Handshake assert_eq!(console().read_char(), 'A'); assert_eq!(console().read_char(), 'B'); assert_eq!(console().read_char(), 'C'); print!("OK1234"); // 6 print!("{}", console().chars_written()); // 3 print!("{}", console().chars_read()); // The QEMU process running this test will be closed by the I/O test harness. cpu::wait_forever(); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. #![feature(custom_test_frameworks)] #![no_main] #![no_std] #![reexport_test_harness_main = "test_main"] #![test_runner(libkernel::test_runner)] use core::time::Duration; use libkernel::{bsp, cpu, exception, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. test_main(); cpu::qemu_exit_success() } /// Simple check that the timer is running. #[kernel_test] fn timer_is_counting() { assert!(time::time_manager().uptime().as_nanos() > 0) } /// Timer resolution must be sufficient. #[kernel_test] fn timer_resolution_is_sufficient() { assert!(time::time_manager().resolution().as_nanos() > 0); assert!(time::time_manager().resolution().as_nanos() < 100) } /// Sanity check spin_for() implementation. #[kernel_test] fn spin_accuracy_check_1_second() { let t1 = time::time_manager().uptime(); time::time_manager().spin_for(Duration::from_secs(1)); let t2 = time::time_manager().uptime(); assert_eq!((t2 - t1).as_secs(), 1) } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. #![feature(format_args_nl)] #![no_main] #![no_std] /// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. /// /// In this test, reaching the panic is a success, because it is called from the synchronous /// exception handler, which is what this test wants to achieve. /// /// It also means that this integration test can not use any other code that calls panic!() directly /// or indirectly. mod panic_exit_success; use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { info!("MMU: {}", string); cpu::qemu_exit_failure() } info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); // If execution reaches here, the memory access above did not cause a page fault exception. cpu::qemu_exit_failure() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. #![feature(format_args_nl)] #![no_main] #![no_std] /// Console tests should time out on the I/O harness in case of panic. mod panic_wait_forever; use core::arch::asm; use libkernel::{bsp, cpu, exception, info, memory, println}; #[inline(never)] fn nested_system_call() { #[cfg(target_arch = "aarch64")] unsafe { asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); } #[cfg(not(target_arch = "aarch64"))] { info!("Not supported yet"); cpu::wait_forever(); } } #[no_mangle] unsafe fn kernel_init() -> ! { use memory::mmu::interface::MMU; exception::handling_init(); bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { info!("MMU: {}", string); cpu::qemu_exit_failure() } info!("Making a dummy system call"); // Calling this inside a function indirectly tests if the link register is restored properly. nested_system_call(); info!("Back from system call!"); // The QEMU process running this test will be closed by the I/O test harness. cpu::wait_forever(); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! IRQ handling sanity tests. #![feature(custom_test_frameworks)] #![no_main] #![no_std] #![reexport_test_harness_main = "test_main"] #![test_runner(libkernel::test_runner)] use libkernel::{bsp, cpu, exception}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { bsp::driver::qemu_bring_up_console(); exception::handling_init(); exception::asynchronous::local_irq_unmask(); test_main(); cpu::qemu_exit_success() } /// Check that IRQ masking works. #[kernel_test] fn local_irq_mask_works() { // Precondition: IRQs are unmasked. assert!(exception::asynchronous::is_local_irq_masked()); exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); // Restore earlier state. exception::asynchronous::local_irq_unmask(); } /// Check that IRQ unmasking works. #[kernel_test] fn local_irq_unmask_works() { // Precondition: IRQs are masked. exception::asynchronous::local_irq_mask(); assert!(!exception::asynchronous::is_local_irq_masked()); exception::asynchronous::local_irq_unmask(); assert!(exception::asynchronous::is_local_irq_masked()); } /// Check that IRQ mask save is saving "something". #[kernel_test] fn local_irq_mask_save_works() { // Precondition: IRQs are unmasked. assert!(exception::asynchronous::is_local_irq_masked()); let first = exception::asynchronous::local_irq_mask_save(); assert!(!exception::asynchronous::is_local_irq_masked()); let second = exception::asynchronous::local_irq_mask_save(); assert_ne!(first, second); exception::asynchronous::local_irq_restore(first); assert!(exception::asynchronous::is_local_irq_masked()); } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 13_exceptions_part2_peripheral_IRQs/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 14_virtual_mem_part2_mmio_remap/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel" ] [profile.release] lto = true ================================================ FILE: 14_virtual_mem_part2_mmio_remap/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 # Optional integration test name. ifdef TEST TEST_ARG = --test $(TEST) else TEST_ARG = --test '*' endif ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = kernel/Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot test_unit test_integration test_unit test_integration: FEATURES += --features test_build ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test_unit test_integration test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER #!/usr/bin/env bash # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure # this script executes from the root. cd $(shell pwd) TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY endef export KERNEL_TEST_RUNNER define test_prepare @mkdir -p target @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh @chmod +x target/kernel_test_runner.sh endef ##------------------------------------------------------------------------------ ## Run unit test(s) ##------------------------------------------------------------------------------ test_unit: $(call color_header, "Compiling unit test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib ##------------------------------------------------------------------------------ ## Run integration test(s) ##------------------------------------------------------------------------------ test_integration: $(call color_header, "Compiling integration test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) test: test_boot test_unit test_integration endif ================================================ FILE: 14_virtual_mem_part2_mmio_remap/README.md ================================================ # Tutorial 14 - Virtual Memory Part 2: MMIO Remap ## tl;dr - We introduce a first set of changes which is eventually needed for separating `kernel` and `user` address spaces. - The memory mapping strategy gets more sophisticated as we do away with `identity mapping` the whole of the board's address space. - Instead, only ranges that are actually needed are mapped: - The `kernel binary` stays `identity mapped` for now. - Device `MMIO regions` are remapped lazily (to a special reserved virtual address region). ## Table of Contents - [Introduction](#introduction) - [Implementation](#implementation) - [A New Mapping API in `src/memory/mmu.rs`](#a-new-mapping-api-in-srcmemorymmutranslationtablers) - [The new APIs in action](#the-new-apis-in-action) - [MMIO Virtual Address Allocation](#mmio-virtual-address-allocation) - [Supporting Changes](#supporting-changes) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction This tutorial is a first step of many needed for enabling `userspace applications` (which we hopefully will have some day in the very distant future). For this, one of the features we want is a clean separation of `kernel` and `user` address spaces. Fortunately, `ARMv8` has convenient architecture support to realize this. The following text and pictue gives some more motivation and technical information. It is quoted from the _[ARM Cortex-A Series Programmer’s Guide for ARMv8-A], Chapter 12.2, Separation of kernel and application Virtual Address spaces_: > Operating systems typically have a number of applications or tasks running concurrently. Each of > these has its own unique set of translation tables and the kernel switches from one to another as > part of the process of switching context between one task and another. However, much of the memory > system is used only by the kernel and has fixed virtual to Physical Address mappings where the > translation table entries rarely change. The ARMv8 architecture provides a number of features to > efficiently handle this requirement. > > The table base addresses are specified in the Translation Table Base Registers `TTBR0_EL1` and > `TTBR1_EL1`. The translation table pointed to by `TTBR0` is selected when the upper bits of the VA > are all 0. `TTBR1` is selected when the upper bits of the VA are all set to 1. [...] > > Figure 12-4 shows how the kernel space can be mapped to the most significant area of memory and > the Virtual Address space associated with each application mapped to the least significant area of > memory. However, both of these are mapped to a much smaller Physical Address space.

This approach is also sometimes called a "[higher half kernel]". To eventually achieve this separation, this tutorial makes a start by changing the following things: 1. Instead of bulk-`identity mapping` the whole of the board's address space, only the particular parts that are needed will be mapped. 1. For now, the `kernel binary` stays identity mapped. This will be changed in the coming tutorials as it is a quite difficult and peculiar exercise to remap the kernel. 1. Device `MMIO regions` are lazily remapped during device driver bringup (using the new `DriverManage` function `instantiate_drivers()`). 1. A dedicated region of virtual addresses that we reserve using `BSP` code and the `linker script` is used for this. 1. We keep using `TTBR0` for the kernel translation tables for now. This will be changed when we remap the `kernel binary` in the coming tutorials. [ARM Cortex-A Series Programmer’s Guide for ARMv8-A]: https://developer.arm.com/documentation/den0024/latest/ [higher half kernel]: https://wiki.osdev.org/Higher_Half_Kernel ## Implementation Until now, the whole address space of the board was identity mapped at once. The **architecture** (`src/_arch/_/memory/**`) and **bsp** (`src/bsp/_/memory/**`) parts of the kernel worked together directly while setting up the translation tables, without any indirection through **generic kernel code** (`src/memory/**`). The way it worked was that the `architectural MMU code` would query the `bsp code` about the start and end of the physical address space, and any special regions in this space that need a mapping that _is not_ normal chacheable DRAM. It would then go ahead and map the whole address space at once and never touch the translation tables again during runtime. Changing in this tutorial, **architecture** and **bsp** code will no longer autonomously create the virtual memory mappings. Instead, this is now orchestrated by the kernel's **generic MMU subsystem code**. ### A New Mapping API in `src/memory/mmu/translation_table.rs` First, we define an interface for operating on `translation tables`: ```rust /// Translation table operations. pub trait TranslationTable { /// Anything that needs to run before any of the other provided functions can be used. /// /// # Safety /// /// - Implementor must ensure that this function can run only once or is harmless if invoked /// multiple times. fn init(&mut self); /// The translation table's base address to be used for programming the MMU. fn phys_base_address(&self) -> Address; /// Map the given virtual memory region to the given physical memory region. unsafe fn map_at( &mut self, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str>; } ``` In order to enable the generic kernel code to manipulate the kernel's translation tables, they must first be made accessible. Until now, they were just a "hidden" struct in the `architectural` MMU driver (`src/arch/.../memory/mmu.rs`). This made sense because the MMU driver code was the only code that needed to be concerned with the table data structure, so having it accessible locally simplified things. Since the tables need to be exposed to the rest of the kernel code now, it makes sense to move them to `BSP` code. Because ultimately, it is the `BSP` that is defining the translation table's properties, such as the size of the virtual address space that the tables need to cover. They are now defined in the global instances region of `src/bsp/.../memory/mmu.rs`. To control access, they are guarded by an `InitStateLock`. ```rust //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. static KERNEL_TABLES: InitStateLock = InitStateLock::new(KernelTranslationTable::new()); ``` The struct `KernelTranslationTable` is a type alias defined in the same file, which in turn gets its definition from an associated type of type `KernelVirtAddrSpace`, which itself is a type alias of `memory::mmu::AddressSpace`. I know this sounds horribly complicated, but in the end this is just some layers of `const generics` whose implementation is scattered between `generic` and `arch` code. This is done to (1) ensure a sane compile-time definition of the translation table struct (by doing various bounds checks), and (2) to separate concerns between generic `MMU` code and specializations that come from the `architectural` part. In the end, these tables can be accessed by calling `bsp::memory::mmu::kernel_translation_tables()`: ```rust /// Return a reference to the kernel's translation tables. pub fn kernel_translation_tables() -> &'static InitStateLock { &KERNEL_TABLES } ``` Finally, the generic kernel code (`src/memory/mmu.rs`) now provides a couple of memory mapping functions that access and manipulate this instance. They are exported for the rest of the kernel to use: ```rust /// Raw mapping of a virtual to physical region in the kernel translation tables. /// /// Prevents mapping into the MMIO range of the tables. pub unsafe fn kernel_map_at( name: &'static str, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str>; /// MMIO remapping in the kernel translation tables. /// /// Typically used by device drivers. pub unsafe fn kernel_map_mmio( name: &'static str, mmio_descriptor: &MMIODescriptor, ) -> Result, &'static str>; /// Map the kernel's binary. Returns the translation table's base address. pub unsafe fn kernel_map_binary() -> Result, &'static str>; /// Enable the MMU and data + instruction caching. pub unsafe fn enable_mmu_and_caching( phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError>; ``` ### The new APIs in action `kernel_map_binary()` and `enable_mmu_and_caching()` are used early in `kernel_init()` to set up virtual memory: ```rust let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { Err(string) => panic!("Error mapping kernel binary: {}", string), Ok(addr) => addr, }; if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { panic!("Enabling MMU failed: {}", e); } ``` Both functions internally use `bsp` and `arch` specific code to achieve their goals. For example, `memory::mmu::kernel_map_binary()` itself wraps around a `bsp` function of the same name (`bsp::memory::mmu::kernel_map_binary()`): ```rust /// Map the kernel binary. pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { generic_mmu::kernel_map_at( "Kernel boot-core stack", // omitted for brevity. )?; generic_mmu::kernel_map_at( "Kernel code and RO data", &virt_code_region(), &kernel_virt_to_phys_region(virt_code_region()), &AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadOnly, execute_never: false, }, )?; generic_mmu::kernel_map_at( "Kernel data and bss", // omitted for brevity. )?; Ok(()) } ``` Another user of the new APIs is the **driver subsystem**. As has been said in the introduction, the goal is to remap the `MMIO` regions of the drivers. To achieve this in a seamless way, some changes to the architecture of the driver subsystem were needed. Until now, the drivers were `static instances` which had their `MMIO addresses` statically set in the constructor. This was fine, because even if virtual memory was activated, only `identity mapping` was used, so the hardcoded addresses would be valid with and without the MMU being active. With `remapped MMIO addresses`, this is not possible anymore, since the remapping will only happen at runtime. Therefore, the new approach is to defer the whole instantiation of the drivers until the remapped addresses are known. To achieve this, in `src/bsp/raspberrypi/drivers.rs`, the static driver instances are now wrapped into a `MaybeUninit` (and are also `mut` now): ```rust static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); static mut GPIO: MaybeUninit = MaybeUninit::uninit(); #[cfg(feature = "bsp_rpi3")] static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); #[cfg(feature = "bsp_rpi4")] static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); ``` Accordingly, new dedicated `instantiate_xyz()` functions have been added, which will be called by the corresponding `driver_xyz()` functions. Here is an example for the `UART`: ```rust /// This must be called only after successful init of the memory subsystem. unsafe fn instantiate_uart() -> Result<(), &'static str> { let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); let virt_addr = memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); Ok(()) } ``` ```rust /// Function needs to ensure that driver registration happens only after correct instantiation. unsafe fn driver_uart() -> Result<(), &'static str> { instantiate_uart()?; let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( PL011_UART.assume_init_ref(), Some(post_init_uart), Some(exception::asynchronous::irq_map::PL011_UART), ); generic_driver::driver_manager().register_driver(uart_descriptor); Ok(()) } ``` The code shows that an `MMIODescriptor` is created first, and then used to remap the MMIO region using `memory::mmu::kernel_map_mmio()`. This function will be discussed in detail in the next chapter. What's important for now is that it returns the new `Virtual Address` of the remapped MMIO region. The constructor of the `UART` driver now also expects a virtual address. Next, a new instance of the `PL011Uart` driver is created, and written into the `PL011_UART` global variable (remember, it is defined as `MaybeUninit = MaybeUninit::uninit()`). Meaning, after this line of code, `PL011_UART` is properly initialized. Only then, the driver is registered with the kernel and thus becomes accessible for the first time. This ensures that nobody can use the UART before its memory has been initialized properly. ### MMIO Virtual Address Allocation Getting back to the remapping part, let's peek inside `memory::mmu::kernel_map_mmio()`. We can see that a `virtual address region` is obtained from an `allocator` before remapping: ```rust pub unsafe fn kernel_map_mmio( name: &'static str, mmio_descriptor: &MMIODescriptor, ) -> Result, &'static str> { // omitted let virt_region = page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; kernel_map_at_unchecked( name, &virt_region, &phys_region, &AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, )?; // omitted } ``` This allocator is defined and implemented in the added file `src/memory/mmu/page_alloc.rs`. Like other parts of the mapping code, its implementation makes use of the newly introduced `PageAddress` and `MemoryRegion` types (in [`src/memory/mmu/types.rs`](kernel/src/memory/mmu/types.rs)), but apart from that is rather straight forward. Therefore, it won't be covered in details here. The more interesting question is: How does the allocator get to learn which VAs it can use? This is happening in the following function, which gets called as part of `memory::mmu::post_enable_init()`, which in turn gets called in `kernel_init()` after the MMU has been turned on. ```rust /// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's /// MMIO VA allocator with it. fn kernel_init_mmio_va_allocator() { let region = bsp::memory::mmu::virt_mmio_remap_region(); page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); } ``` Again, it is the `BSP` that provides the information. The `BSP` itself indirectly gets it from the linker script. In it, we have defined an `8 MiB` region right after the `.data` segment: ```ld.s __data_end_exclusive = .; /*********************************************************************************************** * MMIO Remap Reserved ***********************************************************************************************/ __mmio_remap_start = .; . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") ``` The two symbols `__mmio_remap_start` and `__mmio_remap_end_exclusive` are used by the `BSP` to learn the VA range. ### Supporting Changes There's a couple of changes more not covered in this tutorial text, but the reader should ideally skim through them: - [`src/memory.rs`](kernel/src/memory.rs) and [`src/memory/mmu/types.rs`](kernel/src/memory/mmu/types.rs) introduce supporting types, like`Address`, `PageAddress` and `MemoryRegion`. It is worth reading their implementations. - [`src/memory/mmu/mapping_record.rs`](kernel/src/memory/mmu/mapping_record.rs) provides the generic kernel code's way of tracking previous memory mappings for use cases such as reusing existing mappings (in case of drivers that have their MMIO ranges in the same `64 KiB` page) or printing mappings statistics. ## Test it When you load the kernel, you can now see that the driver's MMIO virtual addresses start right after the `.data` section: Raspberry Pi 3: ```console $ make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 65 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.740694] mingo version 0.14.0 [ 0.740902] Booting on: Raspberry Pi 3 [ 0.741357] MMU online: [ 0.741649] ------------------------------------------------------------------------------------------------------------------------------------------- [ 0.743393] Virtual Physical Size Attr Entity [ 0.745138] ------------------------------------------------------------------------------------------------------------------------------------------- [ 0.746883] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack [ 0.748486] 0x0000_0000_0008_0000..0x0000_0000_0008_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data [ 0.750099] 0x0000_0000_0009_0000..0x0000_0000_000e_ffff --> 0x00_0009_0000..0x00_000e_ffff | 384 KiB | C RW XN | Kernel data and bss [ 0.751670] 0x0000_0000_000f_0000..0x0000_0000_000f_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART [ 0.753187] | BCM GPIO [ 0.754638] 0x0000_0000_0010_0000..0x0000_0000_0010_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Interrupt Controller [ 0.756264] ------------------------------------------------------------------------------------------------------------------------------------------- ``` Raspberry Pi 4: ```console $ BSP=rpi4 make chainboot [...] Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 4 [ML] Requesting binary [MP] ⏩ Pushing 65 KiB =========================================🦀 100% 0 KiB/s Time: 00:00:00 [ML] Loaded! Executing the payload now [ 0.736136] mingo version 0.14.0 [ 0.736170] Booting on: Raspberry Pi 4 [ 0.736625] MMU online: [ 0.736918] ------------------------------------------------------------------------------------------------------------------------------------------- [ 0.738662] Virtual Physical Size Attr Entity [ 0.740406] ------------------------------------------------------------------------------------------------------------------------------------------- [ 0.742151] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack [ 0.743754] 0x0000_0000_0008_0000..0x0000_0000_0008_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data [ 0.745368] 0x0000_0000_0009_0000..0x0000_0000_000d_ffff --> 0x00_0009_0000..0x00_000d_ffff | 320 KiB | C RW XN | Kernel data and bss [ 0.746938] 0x0000_0000_000e_0000..0x0000_0000_000e_ffff --> 0x00_fe20_0000..0x00_fe20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART [ 0.748455] | BCM GPIO [ 0.749907] 0x0000_0000_000f_0000..0x0000_0000_000f_ffff --> 0x00_ff84_0000..0x00_ff84_ffff | 64 KiB | Dev RW XN | GICv2 GICD [ 0.751380] | GICV2 GICC [ 0.752853] ------------------------------------------------------------------------------------------------------------------------------------------- ``` ## Diff to previous ```diff diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml --- 13_exceptions_part2_peripheral_IRQs/kernel/Cargo.toml +++ 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.13.0" +version = "0.14.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -14,10 +14,14 @@ //! crate::memory::mmu::translation_table::arch_translation_table use crate::{ - bsp, memory, - memory::mmu::{ - arch_mmu::{Granule512MiB, Granule64KiB}, - AccessPermissions, AttributeFields, MemAttributes, + bsp, + memory::{ + self, + mmu::{ + arch_mmu::{Granule512MiB, Granule64KiB}, + AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, + }, + Address, Physical, Virtual, }, }; use core::convert; @@ -121,12 +125,9 @@ } trait StartAddr { - fn phys_start_addr_u64(&self) -> u64; - fn phys_start_addr_usize(&self) -> usize; + fn phys_start_addr(&self) -> Address; } -const NUM_LVL2_TABLES: usize = bsp::memory::mmu::KernelAddrSpace::SIZE >> Granule512MiB::SHIFT; - //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- @@ -141,10 +142,10 @@ /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], -} -/// A translation table type for the kernel space. -pub type KernelTranslationTable = FixedSizeTranslationTable; + /// Have the tables been initialized? + initialized: bool, +} //-------------------------------------------------------------------------------------------------- // Private Code @@ -152,12 +153,8 @@ // The binary is still identity mapped, so we don't need to convert here. impl StartAddr for [T; N] { - fn phys_start_addr_u64(&self) -> u64 { - self as *const T as u64 - } - - fn phys_start_addr_usize(&self) -> usize { - self as *const _ as usize + fn phys_start_addr(&self) -> Address { + Address::new(self as *const _ as usize) } } @@ -170,10 +167,10 @@ } /// Create an instance pointing to the supplied address. - pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: usize) -> Self { + pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { let val = InMemoryRegister::::new(0); - let shifted = phys_next_lvl_table_addr >> Granule64KiB::SHIFT; + let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; val.write( STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + STAGE1_TABLE_DESCRIPTOR::TYPE::Table @@ -230,12 +227,15 @@ } /// Create an instance. - pub fn from_output_addr(phys_output_addr: usize, attribute_fields: &AttributeFields) -> Self { + pub fn from_output_page_addr( + phys_output_page_addr: PageAddress, + attribute_fields: &AttributeFields, + ) -> Self { let val = InMemoryRegister::::new(0); - let shifted = phys_output_addr as u64 >> Granule64KiB::SHIFT; + let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; val.write( - STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted) + STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + STAGE1_PAGE_DESCRIPTOR::AF::True + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + STAGE1_PAGE_DESCRIPTOR::VALID::True @@ -244,50 +244,133 @@ Self { value: val.get() } } + + /// Returns the valid bit. + fn is_valid(&self) -> bool { + InMemoryRegister::::new(self.value) + .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) + } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- +impl memory::mmu::AssociatedTranslationTable + for memory::mmu::AddressSpace +where + [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, +{ + type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; +} + impl FixedSizeTranslationTable { /// Create an instance. + #[allow(clippy::assertions_on_constants)] pub const fn new() -> Self { + assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); + // Can't have a zero-sized address space. assert!(NUM_TABLES > 0); Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], + initialized: false, } } - /// Iterates over all static translation table entries and fills them at once. - /// - /// # Safety - /// - /// - Modifies a `static mut`. Ensure it only happens from here. - pub unsafe fn populate_tt_entries(&mut self) -> Result<(), &'static str> { - for (l2_nr, l2_entry) in self.lvl2.iter_mut().enumerate() { - *l2_entry = - TableDescriptor::from_next_lvl_table_addr(self.lvl3[l2_nr].phys_start_addr_usize()); + /// Helper to calculate the lvl2 and lvl3 indices from an address. + #[inline(always)] + fn lvl2_lvl3_index_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<(usize, usize), &'static str> { + let addr = virt_page_addr.into_inner().as_usize(); + let lvl2_index = addr >> Granule512MiB::SHIFT; + let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; - for (l3_nr, l3_entry) in self.lvl3[l2_nr].iter_mut().enumerate() { - let virt_addr = (l2_nr << Granule512MiB::SHIFT) + (l3_nr << Granule64KiB::SHIFT); + if lvl2_index > (NUM_TABLES - 1) { + return Err("Virtual page is out of bounds of translation table"); + } - let (phys_output_addr, attribute_fields) = - bsp::memory::mmu::virt_mem_layout().virt_addr_properties(virt_addr)?; + Ok((lvl2_index, lvl3_index)) + } - *l3_entry = PageDescriptor::from_output_addr(phys_output_addr, &attribute_fields); - } + /// Sets the PageDescriptor corresponding to the supplied page address. + /// + /// Doesn't allow overriding an already valid page. + #[inline(always)] + fn set_page_descriptor_from_page_addr( + &mut self, + virt_page_addr: PageAddress, + new_desc: &PageDescriptor, + ) -> Result<(), &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &mut self.lvl3[lvl2_index][lvl3_index]; + + if desc.is_valid() { + return Err("Virtual page is already mapped"); } + *desc = *new_desc; Ok(()) } +} - /// The translation table's base address to be used for programming the MMU. - pub fn phys_base_address(&self) -> u64 { - self.lvl2.phys_start_addr_u64() +//------------------------------------------------------------------------------ +// OS Interface Code +//------------------------------------------------------------------------------ + +impl memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable +{ + fn init(&mut self) { + if self.initialized { + return; + } + + // Populate the l2 entries. + for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { + let phys_table_addr = self.lvl3[lvl2_nr].phys_start_addr(); + + let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); + *lvl2_entry = new_desc; + } + + self.initialized = true; + } + + fn phys_base_address(&self) -> Address { + self.lvl2.phys_start_addr() + } + + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + assert!(self.initialized, "Translation tables not initialized"); + + if virt_region.size() != phys_region.size() { + return Err("Tried to map memory regions with unequal sizes"); + } + + if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() + { + return Err("Tried to map outside of physical address space"); + } + + let iter = phys_region.into_iter().zip(virt_region.into_iter()); + for (phys_page_addr, virt_page_addr) in iter { + let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); + let virt_page = virt_page_addr; + + self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; + } + + Ok(()) } } @@ -296,6 +379,9 @@ //-------------------------------------------------------------------------------------------------- #[cfg(test)] +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; + +#[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/_arch/aarch64/memory/mmu.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs @@ -15,7 +15,7 @@ use crate::{ bsp, memory, - memory::mmu::{translation_table::KernelTranslationTable, TranslationGranule}, + memory::{mmu::TranslationGranule, Address, Physical}, }; use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; @@ -46,13 +46,6 @@ // Global instances //-------------------------------------------------------------------------------------------------- -/// The kernel translation tables. -/// -/// # Safety -/// -/// - Supposed to land in `.bss`. Therefore, ensure that all initial member values boil down to "0". -static mut KERNEL_TABLES: KernelTranslationTable = KernelTranslationTable::new(); - static MMU: MemoryManagementUnit = MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- @@ -87,7 +80,7 @@ /// Configure various settings of stage 1 of the EL1 translation regime. fn configure_translation_control(&self) { - let t0sz = (64 - bsp::memory::mmu::KernelAddrSpace::SIZE_SHIFT) as u64; + let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used @@ -119,7 +112,10 @@ use memory::mmu::MMUEnableError; impl memory::mmu::interface::MMU for MemoryManagementUnit { - unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError> { + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } @@ -134,13 +130,8 @@ // Prepare the memory attribute indirection register. self.set_up_mair(); - // Populate translation tables. - KERNEL_TABLES - .populate_tt_entries() - .map_err(MMUEnableError::Other)?; - // Set the "Translation Table Base Register". - TTBR0_EL1.set_baddr(KERNEL_TABLES.phys_base_address()); + TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); self.configure_translation_control(); @@ -163,33 +154,3 @@ SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } } - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use core::{cell::UnsafeCell, ops::Range}; - use test_macros::kernel_test; - - /// Check if KERNEL_TABLES is in .bss. - #[kernel_test] - fn kernel_tables_in_bss() { - extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_exclusive: UnsafeCell; - } - - let bss_range = unsafe { - Range { - start: __bss_start.get(), - end: __bss_end_exclusive.get(), - } - }; - let kernel_tables_addr = unsafe { &KERNEL_TABLES as *const _ as usize as *mut u64 }; - - assert!(bss_range.contains(&kernel_tables_addr)); - } -} diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs @@ -4,7 +4,11 @@ //! GICC Driver - GIC CPU interface. -use crate::{bsp::device_driver::common::MMIODerefWrapper, exception}; +use crate::{ + bsp::device_driver::common::MMIODerefWrapper, + exception, + memory::{Address, Virtual}, +}; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, @@ -73,7 +77,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { registers: Registers::new(mmio_start_addr), } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs @@ -8,7 +8,9 @@ //! - SPI - Shared Peripheral Interrupt. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, state, synchronization, + bsp::device_driver::common::MMIODerefWrapper, + memory::{Address, Virtual}, + state, synchronization, synchronization::IRQSafeNullLock, }; use tock_registers::{ @@ -128,7 +130,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { shared_registers: IRQSafeNullLock::new(SharedRegisters::new(mmio_start_addr)), banked_registers: BankedRegisters::new(mmio_start_addr), diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/arm/gicv2.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs @@ -81,7 +81,9 @@ use crate::{ bsp::{self, device_driver::common::BoundedUsize}, - cpu, driver, exception, synchronization, + cpu, driver, exception, + memory::{Address, Virtual}, + synchronization, synchronization::InitStateLock, }; @@ -125,7 +127,10 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(gicd_mmio_start_addr: usize, gicc_mmio_start_addr: usize) -> Self { + pub const unsafe fn new( + gicd_mmio_start_addr: Address, + gicc_mmio_start_addr: Address, + ) -> Self { Self { gicd: gicd::GICD::new(gicd_mmio_start_addr), gicc: gicc::GICC::new(gicc_mmio_start_addr), diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs @@ -5,8 +5,12 @@ //! GPIO Driver. use crate::{ - bsp::device_driver::common::MMIODerefWrapper, driver, exception::asynchronous::IRQNumber, - synchronization, synchronization::IRQSafeNullLock, + bsp::device_driver::common::MMIODerefWrapper, + driver, + exception::asynchronous::IRQNumber, + memory::{Address, Virtual}, + synchronization, + synchronization::IRQSafeNullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, @@ -131,7 +135,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { registers: Registers::new(mmio_start_addr), } @@ -198,7 +202,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { inner: IRQSafeNullLock::new(GPIOInner::new(mmio_start_addr)), } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs @@ -11,7 +11,9 @@ use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, - exception, synchronization, + exception, + memory::{Address, Virtual}, + synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; use tock_registers::{ @@ -79,7 +81,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), ro_registers: ReadOnlyRegisters::new(mmio_start_addr), diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs @@ -10,6 +10,7 @@ bsp::device_driver::common::BoundedUsize, driver, exception::{self, asynchronous::IRQHandlerDescriptor}, + memory::{Address, Virtual}, }; use core::fmt; @@ -91,7 +92,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(periph_mmio_start_addr: usize) -> Self { + pub const unsafe fn new(periph_mmio_start_addr: Address) -> Self { Self { periph: peripheral_ic::PeripheralIC::new(periph_mmio_start_addr), } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs @@ -13,6 +13,7 @@ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception::{self, asynchronous::IRQNumber}, + memory::{Address, Virtual}, synchronization, synchronization::IRQSafeNullLock, }; @@ -244,7 +245,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, @@ -395,7 +396,7 @@ /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. - pub const unsafe fn new(mmio_start_addr: usize) -> Self { + pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/device_driver/common.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs @@ -4,6 +4,7 @@ //! Common device driver code. +use crate::memory::{Address, Virtual}; use core::{fmt, marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- @@ -11,7 +12,7 @@ //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { - start_addr: usize, + start_addr: Address, phantom: PhantomData T>, } @@ -25,7 +26,7 @@ impl MMIODerefWrapper { /// Create an instance. - pub const unsafe fn new(start_addr: usize) -> Self { + pub const unsafe fn new(start_addr: Address) -> Self { Self { start_addr, phantom: PhantomData, @@ -37,7 +38,7 @@ type Target = T; fn deref(&self) -> &Self::Target { - unsafe { &*(self.start_addr as *const _) } + unsafe { &*(self.start_addr.as_usize() as *const _) } } } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/driver.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs @@ -9,52 +9,109 @@ bsp::device_driver, console, driver as generic_driver, exception::{self as generic_exception}, + memory, + memory::mmu::MMIODescriptor, +}; +use core::{ + mem::MaybeUninit, + sync::atomic::{AtomicBool, Ordering}, }; -use core::sync::atomic::{AtomicBool, Ordering}; //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- -static PL011_UART: device_driver::PL011Uart = - unsafe { device_driver::PL011Uart::new(mmio::PL011_UART_START) }; -static GPIO: device_driver::GPIO = unsafe { device_driver::GPIO::new(mmio::GPIO_START) }; +static mut PL011_UART: MaybeUninit = MaybeUninit::uninit(); +static mut GPIO: MaybeUninit = MaybeUninit::uninit(); #[cfg(feature = "bsp_rpi3")] -static INTERRUPT_CONTROLLER: device_driver::InterruptController = - unsafe { device_driver::InterruptController::new(mmio::PERIPHERAL_IC_START) }; +static mut INTERRUPT_CONTROLLER: MaybeUninit = + MaybeUninit::uninit(); #[cfg(feature = "bsp_rpi4")] -static INTERRUPT_CONTROLLER: device_driver::GICv2 = - unsafe { device_driver::GICv2::new(mmio::GICD_START, mmio::GICC_START) }; +static mut INTERRUPT_CONTROLLER: MaybeUninit = MaybeUninit::uninit(); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_uart() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::PL011_UART_START, mmio::PL011_UART_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::PL011Uart::COMPATIBLE, &mmio_descriptor)?; + + PL011_UART.write(device_driver::PL011Uart::new(virt_addr)); + + Ok(()) +} + /// This must be called only after successful init of the UART driver. -fn post_init_uart() -> Result<(), &'static str> { - console::register_console(&PL011_UART); +unsafe fn post_init_uart() -> Result<(), &'static str> { + console::register_console(PL011_UART.assume_init_ref()); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +unsafe fn instantiate_gpio() -> Result<(), &'static str> { + let mmio_descriptor = MMIODescriptor::new(mmio::GPIO_START, mmio::GPIO_SIZE); + let virt_addr = + memory::mmu::kernel_map_mmio(device_driver::GPIO::COMPATIBLE, &mmio_descriptor)?; + + GPIO.write(device_driver::GPIO::new(virt_addr)); Ok(()) } /// This must be called only after successful init of the GPIO driver. -fn post_init_gpio() -> Result<(), &'static str> { - GPIO.map_pl011_uart(); +unsafe fn post_init_gpio() -> Result<(), &'static str> { + GPIO.assume_init_ref().map_pl011_uart(); + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi3")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let periph_mmio_descriptor = + MMIODescriptor::new(mmio::PERIPHERAL_IC_START, mmio::PERIPHERAL_IC_SIZE); + let periph_virt_addr = memory::mmu::kernel_map_mmio( + device_driver::InterruptController::COMPATIBLE, + &periph_mmio_descriptor, + )?; + + INTERRUPT_CONTROLLER.write(device_driver::InterruptController::new(periph_virt_addr)); + + Ok(()) +} + +/// This must be called only after successful init of the memory subsystem. +#[cfg(feature = "bsp_rpi4")] +unsafe fn instantiate_interrupt_controller() -> Result<(), &'static str> { + let gicd_mmio_descriptor = MMIODescriptor::new(mmio::GICD_START, mmio::GICD_SIZE); + let gicd_virt_addr = memory::mmu::kernel_map_mmio("GICv2 GICD", &gicd_mmio_descriptor)?; + + let gicc_mmio_descriptor = MMIODescriptor::new(mmio::GICC_START, mmio::GICC_SIZE); + let gicc_virt_addr = memory::mmu::kernel_map_mmio("GICV2 GICC", &gicc_mmio_descriptor)?; + + INTERRUPT_CONTROLLER.write(device_driver::GICv2::new(gicd_virt_addr, gicc_virt_addr)); + Ok(()) } /// This must be called only after successful init of the interrupt controller driver. -fn post_init_interrupt_controller() -> Result<(), &'static str> { - generic_exception::asynchronous::register_irq_manager(&INTERRUPT_CONTROLLER); +unsafe fn post_init_interrupt_controller() -> Result<(), &'static str> { + generic_exception::asynchronous::register_irq_manager(INTERRUPT_CONTROLLER.assume_init_ref()); Ok(()) } -fn driver_uart() -> Result<(), &'static str> { +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_uart() -> Result<(), &'static str> { + instantiate_uart()?; + let uart_descriptor = generic_driver::DeviceDriverDescriptor::new( - &PL011_UART, + PL011_UART.assume_init_ref(), Some(post_init_uart), Some(exception::asynchronous::irq_map::PL011_UART), ); @@ -63,17 +120,26 @@ Ok(()) } -fn driver_gpio() -> Result<(), &'static str> { - let gpio_descriptor = - generic_driver::DeviceDriverDescriptor::new(&GPIO, Some(post_init_gpio), None); +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_gpio() -> Result<(), &'static str> { + instantiate_gpio()?; + + let gpio_descriptor = generic_driver::DeviceDriverDescriptor::new( + GPIO.assume_init_ref(), + Some(post_init_gpio), + None, + ); generic_driver::driver_manager().register_driver(gpio_descriptor); Ok(()) } -fn driver_interrupt_controller() -> Result<(), &'static str> { +/// Function needs to ensure that driver registration happens only after correct instantiation. +unsafe fn driver_interrupt_controller() -> Result<(), &'static str> { + instantiate_interrupt_controller()?; + let interrupt_controller_descriptor = generic_driver::DeviceDriverDescriptor::new( - &INTERRUPT_CONTROLLER, + INTERRUPT_CONTROLLER.assume_init_ref(), Some(post_init_interrupt_controller), None, ); @@ -109,5 +175,10 @@ /// than on real hardware due to QEMU's abstractions. #[cfg(feature = "test_build")] pub fn qemu_bring_up_console() { - console::register_console(&PL011_UART); + use crate::cpu; + + unsafe { + instantiate_uart().unwrap_or_else(|_| cpu::qemu_exit_failure()); + console::register_console(PL011_UART.assume_init_ref()); + }; } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/kernel.ld +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld @@ -38,7 +38,7 @@ ***********************************************************************************************/ .boot_core_stack (NOLOAD) : { - /* ^ */ + __boot_core_stack_start = .; /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ @@ -67,6 +67,7 @@ /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ + __data_start = .; .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ @@ -78,6 +79,18 @@ __bss_end_exclusive = .; } :segment_data + . = ALIGN(PAGE_SIZE); + __data_end_exclusive = .; + + /*********************************************************************************************** + * MMIO Remap Reserved + ***********************************************************************************************/ + __mmio_remap_start = .; + . += 8 * 1024 * 1024; + __mmio_remap_end_exclusive = .; + + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + /*********************************************************************************************** * Misc ***********************************************************************************************/ diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory/mmu.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -4,70 +4,163 @@ //! BSP Memory Management Unit. -use super::map as memory_map; -use crate::memory::mmu::*; -use core::ops::RangeInclusive; +use crate::{ + memory::{ + mmu::{ + self as generic_mmu, AccessPermissions, AddressSpace, AssociatedTranslationTable, + AttributeFields, MemAttributes, MemoryRegion, PageAddress, TranslationGranule, + }, + Physical, Virtual, + }, + synchronization::InitStateLock, +}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +type KernelTranslationTable = + ::TableStartFromBottom; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- -/// The kernel's address space defined by this BSP. -pub type KernelAddrSpace = AddressSpace<{ memory_map::END_INCLUSIVE + 1 }>; +/// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to +/// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. +pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; + +/// The kernel's virtual address space defined by this BSP. +pub type KernelVirtAddrSpace = AddressSpace<{ 1024 * 1024 * 1024 }>; -const NUM_MEM_RANGES: usize = 2; +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- -/// The virtual memory layout. +/// The kernel translation tables. /// -/// The layout must contain only special ranges, aka anything that is _not_ normal cacheable DRAM. -/// It is agnostic of the paging granularity that the architecture's MMU will use. -pub static LAYOUT: KernelVirtualLayout = KernelVirtualLayout::new( - memory_map::END_INCLUSIVE, - [ - TranslationDescriptor { - name: "Kernel code and RO data", - virtual_range: code_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadOnly, - execute_never: false, - }, - }, - TranslationDescriptor { - name: "Device MMIO", - virtual_range: mmio_range_inclusive, - physical_range_translation: Translation::Identity, - attribute_fields: AttributeFields { - mem_attributes: MemAttributes::Device, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - }, - ], -); +/// It is mandatory that InitStateLock is transparent. +/// +/// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. +/// There is a unit tests that checks this porperty. +static KERNEL_TABLES: InitStateLock = + InitStateLock::new(KernelTranslationTable::new()); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- -fn code_range_inclusive() -> RangeInclusive { - // Notice the subtraction to turn the exclusive end into an inclusive end. - #[allow(clippy::range_minus_one)] - RangeInclusive::new(super::code_start(), super::code_end_exclusive() - 1) +/// Helper function for calculating the number of pages the given parameter spans. +const fn size_to_num_pages(size: usize) -> usize { + assert!(size > 0); + assert!(size modulo KernelGranule::SIZE == 0); + + size >> KernelGranule::SHIFT +} + +/// The code pages of the kernel binary. +fn virt_code_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::code_size()); + + let start_page_addr = super::virt_code_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The data pages of the kernel binary. +fn virt_data_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::data_size()); + + let start_page_addr = super::virt_data_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// The boot core stack pages. +fn virt_boot_core_stack_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::boot_core_stack_size()); + + let start_page_addr = super::virt_boot_core_stack_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } -fn mmio_range_inclusive() -> RangeInclusive { - RangeInclusive::new(memory_map::mmio::START, memory_map::mmio::END_INCLUSIVE) +// The binary is still identity mapped, so use this trivial conversion function for mapping below. + +fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { + MemoryRegion::new( + PageAddress::from(virt_region.start_page_addr().into_inner().as_usize()), + PageAddress::from( + virt_region + .end_exclusive_page_addr() + .into_inner() + .as_usize(), + ), + ) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- -/// Return a reference to the virtual memory layout. -pub fn virt_mem_layout() -> &'static KernelVirtualLayout { - &LAYOUT +/// Return a reference to the kernel's translation tables. +pub fn kernel_translation_tables() -> &'static InitStateLock { + &KERNEL_TABLES +} + +/// The MMIO remap pages. +pub fn virt_mmio_remap_region() -> MemoryRegion { + let num_pages = size_to_num_pages(super::mmio_remap_size()); + + let start_page_addr = super::virt_mmio_remap_start(); + let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); + + MemoryRegion::new(start_page_addr, end_exclusive_page_addr) +} + +/// Map the kernel binary. +/// +/// # Safety +/// +/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. +pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { + generic_mmu::kernel_map_at( + "Kernel boot-core stack", + &virt_boot_core_stack_region(), + &kernel_virt_to_phys_region(virt_boot_core_stack_region()), + &AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + generic_mmu::kernel_map_at( + "Kernel code and RO data", + &virt_code_region(), + &kernel_virt_to_phys_region(virt_code_region()), + &AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadOnly, + execute_never: false, + }, + )?; + + generic_mmu::kernel_map_at( + "Kernel data and bss", + &virt_data_region(), + &kernel_virt_to_phys_region(virt_data_region()), + &AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + Ok(()) } //-------------------------------------------------------------------------------------------------- @@ -77,38 +170,60 @@ #[cfg(test)] mod tests { use super::*; + use core::{cell::UnsafeCell, ops::Range}; use test_macros::kernel_test; /// Check alignment of the kernel's virtual memory layout sections. #[kernel_test] fn virt_mem_layout_sections_are_64KiB_aligned() { - const SIXTYFOUR_KIB: usize = 65536; - - for i in LAYOUT.inner().iter() { - let start: usize = *(i.virtual_range)().start(); - let end: usize = *(i.virtual_range)().end() + 1; - - assert_eq!(start modulo SIXTYFOUR_KIB, 0); - assert_eq!(end modulo SIXTYFOUR_KIB, 0); - assert!(end >= start); + for i in [ + virt_boot_core_stack_region, + virt_code_region, + virt_data_region, + ] + .iter() + { + let start = i().start_page_addr().into_inner(); + let end_exclusive = i().end_exclusive_page_addr().into_inner(); + + assert!(start.is_page_aligned()); + assert!(end_exclusive.is_page_aligned()); + assert!(end_exclusive >= start); } } /// Ensure the kernel's virtual memory layout is free of overlaps. #[kernel_test] fn virt_mem_layout_has_no_overlaps() { - let layout = virt_mem_layout().inner(); - - for (i, first) in layout.iter().enumerate() { - for second in layout.iter().skip(i + 1) { - let first_range = first.virtual_range; - let second_range = second.virtual_range; - - assert!(!first_range().contains(second_range().start())); - assert!(!first_range().contains(second_range().end())); - assert!(!second_range().contains(first_range().start())); - assert!(!second_range().contains(first_range().end())); + let layout = [ + virt_boot_core_stack_region(), + virt_code_region(), + virt_data_region(), + ]; + + for (i, first_range) in layout.iter().enumerate() { + for second_range in layout.iter().skip(i + 1) { + assert!(!first_range.overlaps(second_range)) } } } + + /// Check if KERNEL_TABLES is in .bss. + #[kernel_test] + fn kernel_tables_in_bss() { + extern "Rust" { + static __bss_start: UnsafeCell; + static __bss_end_exclusive: UnsafeCell; + } + + let bss_range = unsafe { + Range { + start: __bss_start.get(), + end: __bss_end_exclusive.get(), + } + }; + let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; + + assert!(bss_range.contains(&kernel_tables_addr)); + } } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/bsp/raspberrypi/memory.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs @@ -10,27 +10,59 @@ //! as the boot core's stack. //! //! +---------------------------------------+ -//! | | 0x0 +//! | | boot_core_stack_start @ 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ -//! | | code_start @ 0x8_0000 +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ -//! | | code_end_exclusive +//! | | data_start == code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ +//! | | data_end_exclusive //! | | +//! +//! +//! +//! +//! +//! The virtual memory layout is as follows: +//! +//! +---------------------------------------+ +//! | | boot_core_stack_start @ 0x0 +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | .text | +//! | .rodata | +//! | .got | +//! | | +//! +---------------------------------------+ +//! | | data_start == code_end_exclusive +//! | .data | +//! | .bss | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_start == data_end_exclusive +//! | VA region for MMIO remapping | +//! | | +//! +---------------------------------------+ +//! | | mmio_remap_end_exclusive //! | | pub mod mmu; +use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- @@ -41,6 +73,15 @@ extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; + + static __data_start: UnsafeCell<()>; + static __data_end_exclusive: UnsafeCell<()>; + + static __mmio_remap_start: UnsafeCell<()>; + static __mmio_remap_end_exclusive: UnsafeCell<()>; + + static __boot_core_stack_start: UnsafeCell<()>; + static __boot_core_stack_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- @@ -50,34 +91,23 @@ /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { - /// The inclusive end address of the memory map. - /// - /// End address + 1 must be power of two. - /// - /// # Note - /// - /// RPi3 and RPi4 boards can have different amounts of RAM. To make our code lean for - /// educational purposes, we set the max size of the address space to 4 GiB regardless of board. - /// This way, we can map the entire range that we need (end of MMIO for RPi4) in one take. - /// - /// However, making this trade-off has the downside of making it possible for the CPU to assert a - /// physical address that is not backed by any DRAM (e.g. accessing an address close to 4 GiB on - /// an RPi3 that comes with 1 GiB of RAM). This would result in a crash or other kind of error. - pub const END_INCLUSIVE: usize = 0xFFFF_FFFF; - - pub const GPIO_OFFSET: usize = 0x0020_0000; - pub const UART_OFFSET: usize = 0x0020_1000; + use super::*; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; - pub const START: usize = 0x3F00_0000; - pub const PERIPHERAL_IC_START: usize = START + 0x0000_B200; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const END_INCLUSIVE: usize = 0x4000_FFFF; + pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); + pub const PERIPHERAL_IC_SIZE: usize = 0x24; + + pub const GPIO_START: Address = Address::new(0x3F20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0x3F20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const END: Address = Address::new(0x4001_0000); } /// Physical devices. @@ -85,13 +115,22 @@ pub mod mmio { use super::*; - pub const START: usize = 0xFE00_0000; - pub const GPIO_START: usize = START + GPIO_OFFSET; - pub const PL011_UART_START: usize = START + UART_OFFSET; - pub const GICD_START: usize = 0xFF84_1000; - pub const GICC_START: usize = 0xFF84_2000; - pub const END_INCLUSIVE: usize = 0xFF84_FFFF; + pub const GPIO_START: Address = Address::new(0xFE20_0000); + pub const GPIO_SIZE: usize = 0xA0; + + pub const PL011_UART_START: Address = Address::new(0xFE20_1000); + pub const PL011_UART_SIZE: usize = 0x48; + + pub const GICD_START: Address = Address::new(0xFF84_1000); + pub const GICD_SIZE: usize = 0x824; + + pub const GICC_START: Address = Address::new(0xFF84_2000); + pub const GICC_SIZE: usize = 0x14; + + pub const END: Address = Address::new(0xFF85_0000); } + + pub const END: Address = mmio::END; } //-------------------------------------------------------------------------------------------------- @@ -104,15 +143,76 @@ /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] -fn code_start() -> usize { - unsafe { __code_start.get() as usize } +fn virt_code_start() -> PageAddress { + PageAddress::from(unsafe { __code_start.get() as usize }) } -/// Exclusive end page address of the code segment. +/// Size of the code segment. +/// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] -fn code_end_exclusive() -> usize { - unsafe { __code_end_exclusive.get() as usize } +fn code_size() -> usize { + unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } +} + +/// Start page address of the data segment. +#[inline(always)] +fn virt_data_start() -> PageAddress { + PageAddress::from(unsafe { __data_start.get() as usize }) +} + +/// Size of the data segment. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn data_size() -> usize { + unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } +} + +/// Start page address of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn virt_mmio_remap_start() -> PageAddress { + PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) +} + +/// Size of the MMIO remap reservation. +/// +/// # Safety +/// +/// - Value is provided by the linker script and must be trusted as-is. +#[inline(always)] +fn mmio_remap_size() -> usize { + unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } +} + +/// Start page address of the boot core's stack. +#[inline(always)] +fn virt_boot_core_stack_start() -> PageAddress { + PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) +} + +/// Size of the boot core's stack. +#[inline(always)] +fn boot_core_stack_size() -> usize { + unsafe { + (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Exclusive end address of the physical address space. +#[inline(always)] +pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { + PageAddress::from(map::END) } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs 14_virtual_mem_part2_mmio_remap/kernel/src/common.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/common.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/common.rs @@ -4,6 +4,30 @@ //! General purpose code. +/// Check if a value is aligned to a given size. +#[inline(always)] +pub const fn is_aligned(value: usize, alignment: usize) -> bool { + assert!(alignment.is_power_of_two()); + + (value & (alignment - 1)) == 0 +} + +/// Align down. +#[inline(always)] +pub const fn align_down(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + value & !(alignment - 1) +} + +/// Align up. +#[inline(always)] +pub const fn align_up(value: usize, alignment: usize) -> usize { + assert!(alignment.is_power_of_two()); + + (value + alignment - 1) & !(alignment - 1) +} + /// Convert a size into human readable format. pub const fn size_human_readable_ceil(size: usize) -> (usize, &'static str) { const KIB: usize = 1024; diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/lib.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs @@ -114,10 +114,13 @@ #![feature(const_option)] #![feature(core_intrinsics)] #![feature(format_args_nl)] +#![feature(generic_const_exprs)] #![feature(int_roundings)] +#![feature(is_sorted)] #![feature(linkage)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] +#![feature(step_trait)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_std] @@ -184,6 +187,17 @@ #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); bsp::driver::qemu_bring_up_console(); test_main(); diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/main.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs @@ -26,14 +26,19 @@ /// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { - use memory::mmu::interface::MMU; - exception::handling_init(); - if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { - panic!("MMU: {}", string); + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); } + memory::mmu::post_enable_init(); + // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); @@ -57,8 +62,8 @@ info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); - info!("MMU online. Special regions:"); - bsp::memory::mmu::virt_mem_layout().print_layout(); + info!("MMU online:"); + memory::mmu::kernel_print_mappings(); let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/mapping_record.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/mapping_record.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs @@ -0,0 +1,238 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! A record of mapped pages. + +use super::{ + AccessPermissions, Address, AttributeFields, MMIODescriptor, MemAttributes, MemoryRegion, + Physical, Virtual, +}; +use crate::{bsp, common, info, synchronization, synchronization::InitStateLock, warn}; + +//-------------------------------------------------------------------------------------------------- +// Private Definitions +//-------------------------------------------------------------------------------------------------- + +/// Type describing a virtual memory mapping. +#[allow(missing_docs)] +#[derive(Copy, Clone)] +struct MappingRecordEntry { + pub users: [Option<&'static str>; 5], + pub phys_start_addr: Address, + pub virt_start_addr: Address, + pub num_pages: usize, + pub attribute_fields: AttributeFields, +} + +struct MappingRecord { + inner: [Option; 12], +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MAPPING_RECORD: InitStateLock = + InitStateLock::new(MappingRecord::new()); + +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- + +impl MappingRecordEntry { + pub fn new( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Self { + Self { + users: [Some(name), None, None, None, None], + phys_start_addr: phys_region.start_addr(), + virt_start_addr: virt_region.start_addr(), + num_pages: phys_region.num_pages(), + attribute_fields: *attr, + } + } + + fn find_next_free_user(&mut self) -> Result<&mut Option<&'static str>, &'static str> { + if let Some(x) = self.users.iter_mut().find(|x| x.is_none()) { + return Ok(x); + }; + + Err("Storage for user info exhausted") + } + + pub fn add_user(&mut self, user: &'static str) -> Result<(), &'static str> { + let x = self.find_next_free_user()?; + *x = Some(user); + Ok(()) + } +} + +impl MappingRecord { + pub const fn new() -> Self { + Self { inner: [None; 12] } + } + + fn size(&self) -> usize { + self.inner.iter().filter(|x| x.is_some()).count() + } + + fn sort(&mut self) { + let upper_bound_exclusive = self.size(); + let entries = &mut self.inner[0..upper_bound_exclusive]; + + if !entries.is_sorted_by_key(|item| item.unwrap().virt_start_addr) { + entries.sort_unstable_by_key(|item| item.unwrap().virt_start_addr) + } + } + + fn find_next_free(&mut self) -> Result<&mut Option, &'static str> { + if let Some(x) = self.inner.iter_mut().find(|x| x.is_none()) { + return Ok(x); + } + + Err("Storage for mapping info exhausted") + } + + fn find_duplicate( + &mut self, + phys_region: &MemoryRegion, + ) -> Option<&mut MappingRecordEntry> { + self.inner + .iter_mut() + .filter_map(|x| x.as_mut()) + .filter(|x| x.attribute_fields.mem_attributes == MemAttributes::Device) + .find(|x| { + if x.phys_start_addr != phys_region.start_addr() { + return false; + } + + if x.num_pages != phys_region.num_pages() { + return false; + } + + true + }) + } + + pub fn add( + &mut self, + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str> { + let x = self.find_next_free()?; + + *x = Some(MappingRecordEntry::new( + name, + virt_region, + phys_region, + attr, + )); + + self.sort(); + + Ok(()) + } + + pub fn print(&self) { + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + info!( + " {:^44} {:^30} {:^7} {:^9} {:^35}", + "Virtual", "Physical", "Size", "Attr", "Entity" + ); + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + + for i in self.inner.iter().flatten() { + let size = i.num_pages * bsp::memory::mmu::KernelGranule::SIZE; + let virt_start = i.virt_start_addr; + let virt_end_inclusive = virt_start + (size - 1); + let phys_start = i.phys_start_addr; + let phys_end_inclusive = phys_start + (size - 1); + + let (size, unit) = common::size_human_readable_ceil(size); + + let attr = match i.attribute_fields.mem_attributes { + MemAttributes::CacheableDRAM => "C", + MemAttributes::Device => "Dev", + }; + + let acc_p = match i.attribute_fields.acc_perms { + AccessPermissions::ReadOnly => "RO", + AccessPermissions::ReadWrite => "RW", + }; + + let xn = if i.attribute_fields.execute_never { + "XN" + } else { + "X" + }; + + info!( + " {}..{} --> {}..{} | {:>3} {} | {:<3} {} {:<2} | {}", + virt_start, + virt_end_inclusive, + phys_start, + phys_end_inclusive, + size, + unit, + attr, + acc_p, + xn, + i.users[0].unwrap() + ); + + for k in i.users[1..].iter() { + if let Some(additional_user) = *k { + info!( + " | {}", + additional_user + ); + } + } + } + + info!(" -------------------------------------------------------------------------------------------------------------------------------------------"); + } +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- +use synchronization::interface::ReadWriteEx; + +/// Add an entry to the mapping info record. +pub fn kernel_add( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + KERNEL_MAPPING_RECORD.write(|mr| mr.add(name, virt_region, phys_region, attr)) +} + +pub fn kernel_find_and_insert_mmio_duplicate( + mmio_descriptor: &MMIODescriptor, + new_user: &'static str, +) -> Option> { + let phys_region: MemoryRegion = (*mmio_descriptor).into(); + + KERNEL_MAPPING_RECORD.write(|mr| { + let dup = mr.find_duplicate(&phys_region)?; + + if let Err(x) = dup.add_user(new_user) { + warn!("{}", x); + } + + Some(dup.virt_start_addr) + }) +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print() { + KERNEL_MAPPING_RECORD.read(|mr| mr.print()); +} diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/page_alloc.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/page_alloc.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2021-2023 Andre Richter + +//! Page allocation. + +use super::MemoryRegion; +use crate::{ + memory::{AddressType, Virtual}, + synchronization::IRQSafeNullLock, + warn, +}; +use core::num::NonZeroUsize; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A page allocator that can be lazyily initialized. +pub struct PageAllocator { + pool: Option>, +} + +//-------------------------------------------------------------------------------------------------- +// Global instances +//-------------------------------------------------------------------------------------------------- + +static KERNEL_MMIO_VA_ALLOCATOR: IRQSafeNullLock> = + IRQSafeNullLock::new(PageAllocator::new()); + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +/// Return a reference to the kernel's MMIO virtual address allocator. +pub fn kernel_mmio_va_allocator() -> &'static IRQSafeNullLock> { + &KERNEL_MMIO_VA_ALLOCATOR +} + +impl PageAllocator { + /// Create an instance. + pub const fn new() -> Self { + Self { pool: None } + } + + /// Initialize the allocator. + pub fn init(&mut self, pool: MemoryRegion) { + if self.pool.is_some() { + warn!("Already initialized"); + return; + } + + self.pool = Some(pool); + } + + /// Allocate a number of pages. + pub fn alloc( + &mut self, + num_requested_pages: NonZeroUsize, + ) -> Result, &'static str> { + if self.pool.is_none() { + return Err("Allocator not initialized"); + } + + self.pool + .as_mut() + .unwrap() + .take_first_n_pages(num_requested_pages) + } +} diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/translation_table.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs @@ -8,7 +8,91 @@ #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] mod arch_translation_table; +use super::{AttributeFields, MemoryRegion}; +use crate::memory::{Address, Physical, Virtual}; + //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- -pub use arch_translation_table::KernelTranslationTable; +#[cfg(target_arch = "aarch64")] +pub use arch_translation_table::FixedSizeTranslationTable; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Translation table interfaces. +pub mod interface { + use super::*; + + /// Translation table operations. + pub trait TranslationTable { + /// Anything that needs to run before any of the other provided functions can be used. + /// + /// # Safety + /// + /// - Implementor must ensure that this function can run only once or is harmless if invoked + /// multiple times. + fn init(&mut self); + + /// The translation table's base address to be used for programming the MMU. + fn phys_base_address(&self) -> Address; + + /// Map the given virtual memory region to the given physical memory region. + /// + /// # Safety + /// + /// - Using wrong attributes can cause multiple issues of different nature in the system. + /// - It is not required that the architectural implementation prevents aliasing. That is, + /// mapping to the same physical memory using multiple virtual addresses, which would + /// break Rust's ownership assumptions. This should be protected against in the kernel's + /// generic MMU code. + unsafe fn map_at( + &mut self, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, + ) -> Result<(), &'static str>; + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use arch_translation_table::MinSizeTranslationTable; + use interface::TranslationTable; + use test_macros::kernel_test; + + /// Sanity checks for the TranslationTable implementation. + #[kernel_test] + fn translationtable_implementation_sanity() { + // This will occupy a lot of space on the stack. + let mut tables = MinSizeTranslationTable::new(); + + tables.init(); + + let virt_start_page_addr: PageAddress = PageAddress::from(0); + let virt_end_exclusive_page_addr: PageAddress = + virt_start_page_addr.checked_offset(5).unwrap(); + + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + + let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; + + unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + } +} diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/types.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu/types.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +// +// Copyright (c) 2020-2023 Andre Richter + +//! Memory Management Unit types. + +use crate::{ + bsp, common, + memory::{Address, AddressType, Physical}, +}; +use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// A wrapper type around [Address] that ensures page alignment. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct PageAddress { + inner: Address, +} + +/// A type that describes a region of memory in quantities of pages. +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct MemoryRegion { + start: PageAddress, + end_exclusive: PageAddress, +} + +/// Architecture agnostic memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum MemAttributes { + CacheableDRAM, + Device, +} + +/// Architecture agnostic access permissions. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub enum AccessPermissions { + ReadOnly, + ReadWrite, +} + +/// Collection of memory attributes. +#[allow(missing_docs)] +#[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] +pub struct AttributeFields { + pub mem_attributes: MemAttributes, + pub acc_perms: AccessPermissions, + pub execute_never: bool, +} + +/// An MMIO descriptor for use in device drivers. +#[derive(Copy, Clone)] +pub struct MMIODescriptor { + start_addr: Address, + end_addr_exclusive: Address, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +//------------------------------------------------------------------------------ +// PageAddress +//------------------------------------------------------------------------------ +impl PageAddress { + /// Unwraps the value. + pub fn into_inner(self) -> Address { + self.inner + } + + /// Calculates the offset from the page address. + /// + /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * + /// page_size`. + pub fn checked_offset(self, count: isize) -> Option { + if count == 0 { + return Some(self); + } + + let delta = count + .unsigned_abs() + .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; + let result = if count.is_positive() { + self.inner.as_usize().checked_add(delta)? + } else { + self.inner.as_usize().checked_sub(delta)? + }; + + Some(Self { + inner: Address::new(result), + }) + } +} + +impl From for PageAddress { + fn from(addr: usize) -> Self { + assert!( + common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), + "Input usize not page aligned" + ); + + Self { + inner: Address::new(addr), + } + } +} + +impl From> for PageAddress { + fn from(addr: Address) -> Self { + assert!(addr.is_page_aligned(), "Input Address not page aligned"); + + Self { inner: addr } + } +} + +impl Step for PageAddress { + fn steps_between(start: &Self, end: &Self) -> Option { + if start > end { + return None; + } + + // Since start <= end, do unchecked arithmetic. + Some( + (end.inner.as_usize() - start.inner.as_usize()) + >> bsp::memory::mmu::KernelGranule::SHIFT, + ) + } + + fn forward_checked(start: Self, count: usize) -> Option { + start.checked_offset(count as isize) + } + + fn backward_checked(start: Self, count: usize) -> Option { + start.checked_offset(-(count as isize)) + } +} + +//------------------------------------------------------------------------------ +// MemoryRegion +//------------------------------------------------------------------------------ +impl MemoryRegion { + /// Create an instance. + pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { + assert!(start <= end_exclusive); + + Self { + start, + end_exclusive, + } + } + + fn as_range(&self) -> Range> { + self.into_iter() + } + + /// Returns the start page address. + pub fn start_page_addr(&self) -> PageAddress { + self.start + } + + /// Returns the start address. + pub fn start_addr(&self) -> Address { + self.start.into_inner() + } + + /// Returns the exclusive end page address. + pub fn end_exclusive_page_addr(&self) -> PageAddress { + self.end_exclusive + } + + /// Returns the exclusive end page address. + pub fn end_inclusive_page_addr(&self) -> PageAddress { + self.end_exclusive.checked_offset(-1).unwrap() + } + + /// Checks if self contains an address. + pub fn contains(&self, addr: Address) -> bool { + let page_addr = PageAddress::from(addr.align_down_page()); + self.as_range().contains(&page_addr) + } + + /// Checks if there is an overlap with another memory region. + pub fn overlaps(&self, other_region: &Self) -> bool { + let self_range = self.as_range(); + + self_range.contains(&other_region.start_page_addr()) + || self_range.contains(&other_region.end_inclusive_page_addr()) + } + + /// Returns the number of pages contained in this region. + pub fn num_pages(&self) -> usize { + PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() + } + + /// Returns the size in bytes of this region. + pub fn size(&self) -> usize { + // Invariant: start <= end_exclusive, so do unchecked arithmetic. + let end_exclusive = self.end_exclusive.into_inner().as_usize(); + let start = self.start.into_inner().as_usize(); + + end_exclusive - start + } + + /// Splits the MemoryRegion like: + /// + /// -------------------------------------------------------------------------------- + /// | | | | | | | | | | | | | | | | | | | + /// -------------------------------------------------------------------------------- + /// ^ ^ ^ + /// | | | + /// left_start left_end_exclusive | + /// | + /// ^ | + /// | | + /// right_start right_end_exclusive + /// + /// Left region is returned to the caller. Right region is the new region for this struct. + pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { + let count: usize = num_pages.into(); + + let left_end_exclusive = self.start.checked_offset(count as isize); + let left_end_exclusive = match left_end_exclusive { + None => return Err("Overflow while calculating left_end_exclusive"), + Some(x) => x, + }; + + if left_end_exclusive > self.end_exclusive { + return Err("Not enough free pages"); + } + + let allocation = Self { + start: self.start, + end_exclusive: left_end_exclusive, + }; + self.start = left_end_exclusive; + + Ok(allocation) + } +} + +impl IntoIterator for MemoryRegion { + type Item = PageAddress; + type IntoIter = Range; + + fn into_iter(self) -> Self::IntoIter { + Range { + start: self.start, + end: self.end_exclusive, + } + } +} + +impl From for MemoryRegion { + fn from(desc: MMIODescriptor) -> Self { + let start = PageAddress::from(desc.start_addr.align_down_page()); + let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); + + Self { + start, + end_exclusive, + } + } +} + +//------------------------------------------------------------------------------ +// MMIODescriptor +//------------------------------------------------------------------------------ + +impl MMIODescriptor { + /// Create an instance. + pub const fn new(start_addr: Address, size: usize) -> Self { + assert!(size > 0); + let end_addr_exclusive = Address::new(start_addr.as_usize() + size); + + Self { + start_addr, + end_addr_exclusive, + } + } + + /// Return the start address. + pub const fn start_addr(&self) -> Address { + self.start_addr + } + + /// Return the exclusive end address. + pub fn end_addr_exclusive(&self) -> Address { + self.end_addr_exclusive + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::Virtual; + use test_macros::kernel_test; + + /// Sanity of [PageAddress] methods. + #[kernel_test] + fn pageaddress_type_method_sanity() { + let page_addr: PageAddress = + PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); + + assert_eq!( + page_addr.checked_offset(-2), + Some(PageAddress::::from(0)) + ); + + assert_eq!( + page_addr.checked_offset(2), + Some(PageAddress::::from( + bsp::memory::mmu::KernelGranule::SIZE * 4 + )) + ); + + assert_eq!( + PageAddress::::from(0).checked_offset(0), + Some(PageAddress::::from(0)) + ); + assert_eq!(PageAddress::::from(0).checked_offset(-1), None); + + let max_page_addr = Address::::new(usize::MAX).align_down_page(); + assert_eq!( + PageAddress::::from(max_page_addr).checked_offset(1), + None + ); + + let zero = PageAddress::::from(0); + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); + } + + /// Sanity of [MemoryRegion] methods. + #[kernel_test] + fn memoryregion_type_method_sanity() { + let zero = PageAddress::::from(0); + let zero_region = MemoryRegion::new(zero, zero); + assert_eq!(zero_region.num_pages(), 0); + assert_eq!(zero_region.size(), 0); + + let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); + let one_region = MemoryRegion::new(zero, one); + assert_eq!(one_region.num_pages(), 1); + assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); + + let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); + let mut three_region = MemoryRegion::new(zero, three); + assert!(three_region.contains(zero.into_inner())); + assert!(!three_region.contains(three.into_inner())); + assert!(three_region.overlaps(&one_region)); + + let allocation = three_region + .take_first_n_pages(NonZeroUsize::new(2).unwrap()) + .unwrap(); + assert_eq!(allocation.num_pages(), 2); + assert_eq!(three_region.num_pages(), 1); + + for (i, alloc) in allocation.into_iter().enumerate() { + assert_eq!( + alloc.into_inner().as_usize(), + i * bsp::memory::mmu::KernelGranule::SIZE + ); + } + } +} diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory/mmu.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs @@ -3,30 +3,24 @@ // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. -//! -//! In order to decouple `BSP` and `arch` parts of the MMU code (to keep them pluggable), this file -//! provides types for composing an architecture-agnostic description of the kernel's virtual memory -//! layout. -//! -//! The `BSP` provides such a description through the `bsp::memory::mmu::virt_mem_layout()` -//! function. -//! -//! The `MMU` driver of the `arch` code uses `bsp::memory::mmu::virt_mem_layout()` to compile and -//! install respective translation tables. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; +mod mapping_record; +mod page_alloc; mod translation_table; +mod types; -use crate::common; -use core::{fmt, ops::RangeInclusive}; +use crate::{ + bsp, + memory::{Address, Physical, Virtual}, + synchronization, warn, +}; +use core::{fmt, num::NonZeroUsize}; -//-------------------------------------------------------------------------------------------------- -// Architectural Public Reexports -//-------------------------------------------------------------------------------------------------- -pub use arch_mmu::mmu; +pub use types::*; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -46,13 +40,15 @@ /// MMU functions. pub trait MMU { - /// Called by the kernel during early init. Supposed to take the translation tables from the - /// `BSP`-supplied `virt_mem_layout()` and install/activate them for the respective MMU. + /// Turns on the MMU for the first time and enables data and instruction caching. /// /// # Safety /// /// - Changes the HW's global state. - unsafe fn enable_mmu_and_caching(&self) -> Result<(), MMUEnableError>; + unsafe fn enable_mmu_and_caching( + &self, + phys_tables_base_addr: Address, + ) -> Result<(), MMUEnableError>; /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; @@ -65,55 +61,51 @@ /// Describes properties of an address space. pub struct AddressSpace; -/// Architecture agnostic translation types. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum Translation { - Identity, - Offset(usize), -} - -/// Architecture agnostic memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum MemAttributes { - CacheableDRAM, - Device, -} - -/// Architecture agnostic access permissions. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub enum AccessPermissions { - ReadOnly, - ReadWrite, -} - -/// Collection of memory attributes. -#[allow(missing_docs)] -#[derive(Copy, Clone)] -pub struct AttributeFields { - pub mem_attributes: MemAttributes, - pub acc_perms: AccessPermissions, - pub execute_never: bool, +/// Intended to be implemented for [`AddressSpace`]. +pub trait AssociatedTranslationTable { + /// A translation table whose address range is: + /// + /// [AS_SIZE - 1, 0] + type TableStartFromBottom; } -/// Architecture agnostic descriptor for a memory range. -#[allow(missing_docs)] -pub struct TranslationDescriptor { - pub name: &'static str, - pub virtual_range: fn() -> RangeInclusive, - pub physical_range_translation: Translation, - pub attribute_fields: AttributeFields, -} +//-------------------------------------------------------------------------------------------------- +// Private Code +//-------------------------------------------------------------------------------------------------- +use interface::MMU; +use synchronization::interface::*; +use translation_table::interface::TranslationTable; + +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Map a region in the kernel's translation tables. +/// +/// No input checks done, input is passed through to the architectural implementation. +/// +/// # Safety +/// +/// - See `map_at()`. +/// - Does not prevent aliasing. +unsafe fn kernel_map_at_unchecked( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .write(|tables| tables.map_at(virt_region, phys_region, attr))?; -/// Type for expressing the kernel's virtual memory layout. -pub struct KernelVirtualLayout { - /// The last (inclusive) address of the address space. - max_virt_addr_inclusive: usize, + if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { + warn!("{}", x); + } - /// Array of descriptors for non-standard (normal cacheable DRAM) memory regions. - inner: [TranslationDescriptor; NUM_SPECIAL_RANGES], + Ok(()) } //-------------------------------------------------------------------------------------------------- @@ -133,6 +125,9 @@ /// The granule's size. pub const SIZE: usize = Self::size_checked(); + /// The granule's mask. + pub const MASK: usize = Self::SIZE - 1; + /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; @@ -160,98 +155,147 @@ } } -impl Default for AttributeFields { - fn default() -> AttributeFields { - AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - } +/// Raw mapping of a virtual to physical region in the kernel translation tables. +/// +/// Prevents mapping into the MMIO range of the tables. +/// +/// # Safety +/// +/// - See `kernel_map_at_unchecked()`. +/// - Does not prevent aliasing. Currently, the callers must be trusted. +pub unsafe fn kernel_map_at( + name: &'static str, + virt_region: &MemoryRegion, + phys_region: &MemoryRegion, + attr: &AttributeFields, +) -> Result<(), &'static str> { + if bsp::memory::mmu::virt_mmio_remap_region().overlaps(virt_region) { + return Err("Attempt to manually map into MMIO region"); } -} -/// Human-readable output of a TranslationDescriptor. -impl fmt::Display for TranslationDescriptor { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Call the function to which self.range points, and dereference the result, which causes - // Rust to copy the value. - let start = *(self.virtual_range)().start(); - let end = *(self.virtual_range)().end(); - let size = end - start + 1; - - let (size, unit) = common::size_human_readable_ceil(size); - - let attr = match self.attribute_fields.mem_attributes { - MemAttributes::CacheableDRAM => "C", - MemAttributes::Device => "Dev", - }; - - let acc_p = match self.attribute_fields.acc_perms { - AccessPermissions::ReadOnly => "RO", - AccessPermissions::ReadWrite => "RW", - }; + kernel_map_at_unchecked(name, virt_region, phys_region, attr)?; - let xn = if self.attribute_fields.execute_never { - "PXN" - } else { - "PX" - }; - - write!( - f, - " {:#010x} - {:#010x} | {: >3} {} | {: <3} {} {: <3} | {}", - start, end, size, unit, attr, acc_p, xn, self.name - ) - } + Ok(()) } -impl KernelVirtualLayout<{ NUM_SPECIAL_RANGES }> { - /// Create a new instance. - pub const fn new(max: usize, layout: [TranslationDescriptor; NUM_SPECIAL_RANGES]) -> Self { - Self { - max_virt_addr_inclusive: max, - inner: layout, - } - } +/// MMIO remapping in the kernel translation tables. +/// +/// Typically used by device drivers. +/// +/// # Safety +/// +/// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. +pub unsafe fn kernel_map_mmio( + name: &'static str, + mmio_descriptor: &MMIODescriptor, +) -> Result, &'static str> { + let phys_region = MemoryRegion::from(*mmio_descriptor); + let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); + + // Check if an identical region has been mapped for another driver. If so, reuse it. + let virt_addr = if let Some(addr) = + mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) + { + addr + // Otherwise, allocate a new region and map it. + } else { + let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { + None => return Err("Requested 0 pages"), + Some(x) => x, + }; - /// For a virtual address, find and return the physical output address and corresponding - /// attributes. - /// - /// If the address is not found in `inner`, return an identity mapped default with normal - /// cacheable DRAM attributes. - pub fn virt_addr_properties( - &self, - virt_addr: usize, - ) -> Result<(usize, AttributeFields), &'static str> { - if virt_addr > self.max_virt_addr_inclusive { - return Err("Address out of range"); - } + let virt_region = + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; - for i in self.inner.iter() { - if (i.virtual_range)().contains(&virt_addr) { - let output_addr = match i.physical_range_translation { - Translation::Identity => virt_addr, - Translation::Offset(a) => a + (virt_addr - (i.virtual_range)().start()), - }; + kernel_map_at_unchecked( + name, + &virt_region, + &phys_region, + &AttributeFields { + mem_attributes: MemAttributes::Device, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }, + )?; + + virt_region.start_addr() + }; + + Ok(virt_addr + offset_into_start_page) +} + +/// Map the kernel's binary. Returns the translation table's base address. +/// +/// # Safety +/// +/// - See [`bsp::memory::mmu::kernel_map_binary()`]. +pub unsafe fn kernel_map_binary() -> Result, &'static str> { + let phys_kernel_tables_base_addr = + bsp::memory::mmu::kernel_translation_tables().write(|tables| { + tables.init(); + tables.phys_base_address() + }); + + bsp::memory::mmu::kernel_map_binary()?; + + Ok(phys_kernel_tables_base_addr) +} + +/// Enable the MMU and data + instruction caching. +/// +/// # Safety +/// +/// - Crucial function during kernel init. Changes the the complete memory view of the processor. +pub unsafe fn enable_mmu_and_caching( + phys_tables_base_addr: Address, +) -> Result<(), MMUEnableError> { + arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) +} + +/// Finish initialization of the MMU subsystem. +pub fn post_enable_init() { + kernel_init_mmio_va_allocator(); +} + +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() +} - return Ok((output_addr, i.attribute_fields)); - } - } +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- - Ok((virt_addr, AttributeFields::default())) - } +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; + use test_macros::kernel_test; - /// Print the memory layout. - pub fn print_layout(&self) { - use crate::info; + /// Check that you cannot map into the MMIO VA range from kernel_map_at(). + #[kernel_test] + fn no_manual_mmio_map() { + let phys_start_page_addr: PageAddress = PageAddress::from(0); + let phys_end_exclusive_page_addr: PageAddress = + phys_start_page_addr.checked_offset(5).unwrap(); + let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); + + let num_pages = NonZeroUsize::new(phys_region.num_pages()).unwrap(); + let virt_region = page_alloc::kernel_mmio_va_allocator() + .lock(|allocator| allocator.alloc(num_pages)) + .unwrap(); - for i in self.inner.iter() { - info!("{}", i); - } - } + let attr = AttributeFields { + mem_attributes: MemAttributes::CacheableDRAM, + acc_perms: AccessPermissions::ReadWrite, + execute_never: true, + }; - #[cfg(test)] - pub fn inner(&self) -> &[TranslationDescriptor; NUM_SPECIAL_RANGES] { - &self.inner + unsafe { + assert_eq!( + kernel_map_at("test", &virt_region, &phys_region, &attr), + Err("Attempt to manually map into MMIO region") + ) + }; } } diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/src/memory.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs @@ -5,3 +5,163 @@ //! Memory Management. pub mod mmu; + +use crate::{bsp, common}; +use core::{ + fmt, + marker::PhantomData, + ops::{Add, Sub}, +}; + +//-------------------------------------------------------------------------------------------------- +// Public Definitions +//-------------------------------------------------------------------------------------------------- + +/// Metadata trait for marking the type of an address. +pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} + +/// Zero-sized type to mark a physical address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Physical {} + +/// Zero-sized type to mark a virtual address. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub enum Virtual {} + +/// Generic address type. +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] +pub struct Address { + value: usize, + _address_type: PhantomData ATYPE>, +} + +//-------------------------------------------------------------------------------------------------- +// Public Code +//-------------------------------------------------------------------------------------------------- + +impl AddressType for Physical {} +impl AddressType for Virtual {} + +impl Address { + /// Create an instance. + pub const fn new(value: usize) -> Self { + Self { + value, + _address_type: PhantomData, + } + } + + /// Convert to usize. + pub const fn as_usize(self) -> usize { + self.value + } + + /// Align down to page size. + #[must_use] + pub const fn align_down_page(self) -> Self { + let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Align up to page size. + #[must_use] + pub const fn align_up_page(self) -> Self { + let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); + + Self::new(aligned) + } + + /// Checks if the address is page aligned. + pub const fn is_page_aligned(&self) -> bool { + common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) + } + + /// Return the address' offset into the corresponding page. + pub const fn offset_into_page(&self) -> usize { + self.value & bsp::memory::mmu::KernelGranule::MASK + } +} + +impl Add for Address { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: usize) -> Self::Output { + match self.value.checked_add(rhs) { + None => panic!("Overflow on Address::add"), + Some(x) => Self::new(x), + } + } +} + +impl Sub> for Address { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Address) -> Self::Output { + match self.value.checked_sub(rhs.value) { + None => panic!("Overflow on Address::sub"), + Some(x) => Self::new(x), + } + } +} + +impl fmt::Display for Address { + // Don't expect to see physical addresses greater than 40 bit. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q3: u8 = ((self.value >> 32) & 0xff) as u8; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:02x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let q4: u16 = ((self.value >> 48) & 0xffff) as u16; + let q3: u16 = ((self.value >> 32) & 0xffff) as u16; + let q2: u16 = ((self.value >> 16) & 0xffff) as u16; + let q1: u16 = (self.value & 0xffff) as u16; + + write!(f, "0x")?; + write!(f, "{:04x}_", q4)?; + write!(f, "{:04x}_", q3)?; + write!(f, "{:04x}_", q2)?; + write!(f, "{:04x}", q1) + } +} + +//-------------------------------------------------------------------------------------------------- +// Testing +//-------------------------------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use test_macros::kernel_test; + + /// Sanity of [Address] methods. + #[kernel_test] + fn address_type_method_sanity() { + let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); + + assert_eq!( + addr.align_down_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE + ); + + assert_eq!( + addr.align_up_page().as_usize(), + bsp::memory::mmu::KernelGranule::SIZE * 2 + ); + + assert!(!addr.is_page_aligned()); + + assert_eq!(addr.offset_into_page(), 100); + } +} diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/tests/00_console_sanity.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs @@ -11,13 +11,24 @@ /// Console tests should time out on the I/O harness in case of panic. mod panic_wait_forever; -use libkernel::{bsp, console, cpu, exception, print}; +use libkernel::{bsp, console, cpu, exception, memory, print}; #[no_mangle] unsafe fn kernel_init() -> ! { use console::console; exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); bsp::driver::qemu_bring_up_console(); // Handshake diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/tests/01_timer_sanity.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs @@ -11,12 +11,23 @@ #![test_runner(libkernel::test_runner)] use core::time::Duration; -use libkernel::{bsp, cpu, exception, time}; +use libkernel::{bsp, cpu, exception, memory, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/tests/02_exception_sync_page_fault.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs @@ -21,19 +21,27 @@ #[no_mangle] unsafe fn kernel_init() -> ! { - use memory::mmu::interface::MMU; - exception::handling_init(); - bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); - if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { - info!("MMU: {}", string); + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => { + info!("Error mapping kernel binary: {}", string); + cpu::qemu_exit_failure() + } + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/tests/03_exception_restore_sanity.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs @@ -30,19 +30,27 @@ #[no_mangle] unsafe fn kernel_init() -> ! { - use memory::mmu::interface::MMU; - exception::handling_init(); - bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); - if let Err(string) = memory::mmu::mmu().enable_mmu_and_caching() { - info!("MMU: {}", string); + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => { + info!("Error mapping kernel binary: {}", string); + cpu::qemu_exit_failure() + } + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } + memory::mmu::post_enable_init(); + bsp::driver::qemu_bring_up_console(); + info!("Making a dummy system call"); // Calling this inside a function indirectly tests if the link register is restored properly. diff -uNr 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs --- 13_exceptions_part2_peripheral_IRQs/kernel/tests/04_exception_irq_sanity.rs +++ 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs @@ -10,14 +10,25 @@ #![reexport_test_harness_main = "test_main"] #![test_runner(libkernel::test_runner)] -use libkernel::{bsp, cpu, exception}; +use libkernel::{bsp, cpu, exception, memory}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { + exception::handling_init(); + + let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { + Err(string) => panic!("Error mapping kernel binary: {}", string), + Ok(addr) => addr, + }; + + if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { + panic!("Enabling MMU failed: {}", e); + } + + memory::mmu::post_enable_init(); bsp::driver::qemu_bring_up_console(); - exception::handling_init(); exception::asynchronous::local_irq_unmask(); test_main(); ``` ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/build.rs ================================================ 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())); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prepares the transition from EL2 to EL1. /// /// # Safety /// /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. /// /// # Safety /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. x0 holds the function argument provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::translation_table::arch_translation_table use crate::{ bsp, memory::{ self, mmu::{ arch_mmu::{Granule512MiB, Granule64KiB}, AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, }, Address, Physical, Virtual, }, }; use core::convert; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, registers::InMemoryRegister, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. register_bitfields! {u64, STAGE1_TABLE_DESCRIPTOR [ /// Physical address of the next descriptor. NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] TYPE OFFSET(1) NUMBITS(1) [ Block = 0, Table = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } // A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. register_bitfields! {u64, STAGE1_PAGE_DESCRIPTOR [ /// Unprivileged execute-never. UXN OFFSET(54) NUMBITS(1) [ False = 0, True = 1 ], /// Privileged execute-never. PXN OFFSET(53) NUMBITS(1) [ False = 0, True = 1 ], /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] /// Access flag. AF OFFSET(10) NUMBITS(1) [ False = 0, True = 1 ], /// Shareability field. SH OFFSET(8) NUMBITS(2) [ OuterShareable = 0b10, InnerShareable = 0b11 ], /// Access Permissions. AP OFFSET(6) NUMBITS(2) [ RW_EL1 = 0b00, RW_EL1_EL0 = 0b01, RO_EL1 = 0b10, RO_EL1_EL0 = 0b11 ], /// Memory attributes index into the MAIR_EL1 register. AttrIndx OFFSET(2) NUMBITS(3) [], TYPE OFFSET(1) NUMBITS(1) [ Reserved_Invalid = 0, Page = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } /// A table descriptor for 64 KiB aperture. /// /// The output points to the next table. #[derive(Copy, Clone)] #[repr(C)] struct TableDescriptor { value: u64, } /// A page descriptor with 64 KiB aperture. /// /// The output points to physical memory. #[derive(Copy, Clone)] #[repr(C)] struct PageDescriptor { value: u64, } trait StartAddr { fn phys_start_addr(&self) -> Address; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB /// aligned, so the lvl3 is put first. #[repr(C)] #[repr(align(65536))] pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], /// Have the tables been initialized? initialized: bool, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- // The binary is still identity mapped, so we don't need to convert here. impl StartAddr for [T; N] { fn phys_start_addr(&self) -> Address { Address::new(self as *const _ as usize) } } impl TableDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance pointing to the supplied address. pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; val.write( STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + STAGE1_TABLE_DESCRIPTOR::VALID::True, ); TableDescriptor { value: val.get() } } } /// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. impl convert::From for tock_registers::fields::FieldValue { fn from(attribute_fields: AttributeFields) -> Self { // Memory attributes. let mut desc = match attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => { STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) } MemAttributes::Device => { STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) } }; // Access Permissions. desc += match attribute_fields.acc_perms { AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, }; // The execute-never attribute is mapped to PXN in AArch64. desc += if attribute_fields.execute_never { STAGE1_PAGE_DESCRIPTOR::PXN::True } else { STAGE1_PAGE_DESCRIPTOR::PXN::False }; // Always set unprivileged exectue-never as long as userspace is not implemented yet. desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; desc } } impl PageDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance. pub fn from_output_page_addr( phys_output_page_addr: PageAddress, attribute_fields: &AttributeFields, ) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; val.write( STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + STAGE1_PAGE_DESCRIPTOR::AF::True + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + STAGE1_PAGE_DESCRIPTOR::VALID::True + (*attribute_fields).into(), ); Self { value: val.get() } } /// Returns the valid bit. fn is_valid(&self) -> bool { InMemoryRegister::::new(self.value) .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AssociatedTranslationTable for memory::mmu::AddressSpace where [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, { type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; } impl FixedSizeTranslationTable { /// Create an instance. #[allow(clippy::assertions_on_constants)] pub const fn new() -> Self { assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); // Can't have a zero-sized address space. assert!(NUM_TABLES > 0); Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], initialized: false, } } /// Helper to calculate the lvl2 and lvl3 indices from an address. #[inline(always)] fn lvl2_lvl3_index_from_page_addr( &self, virt_page_addr: PageAddress, ) -> Result<(usize, usize), &'static str> { let addr = virt_page_addr.into_inner().as_usize(); let lvl2_index = addr >> Granule512MiB::SHIFT; let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; if lvl2_index > (NUM_TABLES - 1) { return Err("Virtual page is out of bounds of translation table"); } Ok((lvl2_index, lvl3_index)) } /// Sets the PageDescriptor corresponding to the supplied page address. /// /// Doesn't allow overriding an already valid page. #[inline(always)] fn set_page_descriptor_from_page_addr( &mut self, virt_page_addr: PageAddress, new_desc: &PageDescriptor, ) -> Result<(), &'static str> { let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; let desc = &mut self.lvl3[lvl2_index][lvl3_index]; if desc.is_valid() { return Err("Virtual page is already mapped"); } *desc = *new_desc; Ok(()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl memory::mmu::translation_table::interface::TranslationTable for FixedSizeTranslationTable { fn init(&mut self) { if self.initialized { return; } // Populate the l2 entries. for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { let phys_table_addr = self.lvl3[lvl2_nr].phys_start_addr(); let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); *lvl2_entry = new_desc; } self.initialized = true; } fn phys_base_address(&self) -> Address { self.lvl2.phys_start_addr() } unsafe fn map_at( &mut self, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str> { assert!(self.initialized, "Translation tables not initialized"); if virt_region.size() != phys_region.size() { return Err("Tried to map memory regions with unequal sizes"); } if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() { return Err("Tried to map outside of physical address space"); } let iter = phys_region.into_iter().zip(virt_region.into_iter()); for (phys_page_addr, virt_page_addr) in iter { let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); let virt_page = virt_page_addr; self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Check if the size of `struct TableDescriptor` is as expected. #[kernel_test] fn size_of_tabledescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } /// Check if the size of `struct PageDescriptor` is as expected. #[kernel_test] fn size_of_pagedescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::arch_mmu use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical}, }; use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Memory Management Unit type. struct MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; /// Constants for indexing the MAIR_EL1. #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static MMU: MemoryManagementUnit = MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AddressSpace { /// Checks for architectural restrictions. pub const fn arch_address_space_size_sanity_checks() { // Size must be at least one full 512 MiB table. assert!((AS_SIZE % Granule512MiB::SIZE) == 0); // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 // version. assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } /// Configure various settings of stage 1 of the EL1 translation regime. fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the MMU instance. pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use memory::mmu::MMUEnableError; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } // Fail early if translation granule is not supported. if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } // Prepare the memory attribute indirection register. self.set_up_mair(); // Set the "Translation Table Base Register". TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); self.configure_translation_control(); // Switch the MMU on. // // First, force all previous changes to be seen before the MMU is enabled. barrier::isb(barrier::SY); // Enable the MMU and turn on data and instruction caching. SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); // Force MMU init to complete before next instruction. barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // 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)); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // 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); }); } } } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // 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()); } } }); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // 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 } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // 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()); } } }); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // 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(); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // 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(()) } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver/common.rs ================================================ // 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) } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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()); }; } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW * * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. * It doesn't mean all of them need actually be loaded. */ PHDRS { segment_boot_core_stack PT_LOAD FLAGS(6); segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); } SECTIONS { . = __rpi_phys_dram_start_addr; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : { __boot_core_stack_start = .; /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __code_start = .; .text : { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ *(.text._start_rust) /* The Rust entry point */ *(.text*) /* Everything else */ } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ __data_start = .; .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { __bss_start = .; *(.bss*); . = ALIGN(16); __bss_end_exclusive = .; } :segment_data . = ALIGN(PAGE_SIZE); __data_end_exclusive = .; /*********************************************************************************************** * MMIO Remap Reserved ***********************************************************************************************/ __mmio_remap_start = .; . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") /*********************************************************************************************** * Misc ***********************************************************************************************/ .got : { *(.got*) } ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") /DISCARD/ : { *(.comment*) } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. use crate::{ memory::{ mmu::{ self as generic_mmu, AccessPermissions, AddressSpace, AssociatedTranslationTable, AttributeFields, MemAttributes, MemoryRegion, PageAddress, TranslationGranule, }, Physical, Virtual, }, synchronization::InitStateLock, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- type KernelTranslationTable = ::TableStartFromBottom; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to /// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; /// The kernel's virtual address space defined by this BSP. pub type KernelVirtAddrSpace = AddressSpace<{ 1024 * 1024 * 1024 }>; //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. /// /// It is mandatory that InitStateLock is transparent. /// /// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. /// There is a unit tests that checks this porperty. static KERNEL_TABLES: InitStateLock = InitStateLock::new(KernelTranslationTable::new()); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Helper function for calculating the number of pages the given parameter spans. const fn size_to_num_pages(size: usize) -> usize { assert!(size > 0); assert!(size % KernelGranule::SIZE == 0); size >> KernelGranule::SHIFT } /// The code pages of the kernel binary. fn virt_code_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::code_size()); let start_page_addr = super::virt_code_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } /// The data pages of the kernel binary. fn virt_data_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::data_size()); let start_page_addr = super::virt_data_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } /// The boot core stack pages. fn virt_boot_core_stack_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::boot_core_stack_size()); let start_page_addr = super::virt_boot_core_stack_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } // The binary is still identity mapped, so use this trivial conversion function for mapping below. fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { MemoryRegion::new( PageAddress::from(virt_region.start_page_addr().into_inner().as_usize()), PageAddress::from( virt_region .end_exclusive_page_addr() .into_inner() .as_usize(), ), ) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the kernel's translation tables. pub fn kernel_translation_tables() -> &'static InitStateLock { &KERNEL_TABLES } /// The MMIO remap pages. pub fn virt_mmio_remap_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::mmio_remap_size()); let start_page_addr = super::virt_mmio_remap_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } /// Map the kernel binary. /// /// # Safety /// /// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { generic_mmu::kernel_map_at( "Kernel boot-core stack", &virt_boot_core_stack_region(), &kernel_virt_to_phys_region(virt_boot_core_stack_region()), &AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, )?; generic_mmu::kernel_map_at( "Kernel code and RO data", &virt_code_region(), &kernel_virt_to_phys_region(virt_code_region()), &AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadOnly, execute_never: false, }, )?; generic_mmu::kernel_map_at( "Kernel data and bss", &virt_data_region(), &kernel_virt_to_phys_region(virt_data_region()), &AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, )?; Ok(()) } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use core::{cell::UnsafeCell, ops::Range}; use test_macros::kernel_test; /// Check alignment of the kernel's virtual memory layout sections. #[kernel_test] fn virt_mem_layout_sections_are_64KiB_aligned() { for i in [ virt_boot_core_stack_region, virt_code_region, virt_data_region, ] .iter() { let start = i().start_page_addr().into_inner(); let end_exclusive = i().end_exclusive_page_addr().into_inner(); assert!(start.is_page_aligned()); assert!(end_exclusive.is_page_aligned()); assert!(end_exclusive >= start); } } /// Ensure the kernel's virtual memory layout is free of overlaps. #[kernel_test] fn virt_mem_layout_has_no_overlaps() { let layout = [ virt_boot_core_stack_region(), virt_code_region(), virt_data_region(), ]; for (i, first_range) in layout.iter().enumerate() { for second_range in layout.iter().skip(i + 1) { assert!(!first_range.overlaps(second_range)) } } } /// Check if KERNEL_TABLES is in .bss. #[kernel_test] fn kernel_tables_in_bss() { extern "Rust" { static __bss_start: UnsafeCell; static __bss_end_exclusive: UnsafeCell; } let bss_range = unsafe { Range { start: __bss_start.get(), end: __bss_end_exclusive.get(), } }; let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; assert!(bss_range.contains(&kernel_tables_addr)); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! //! The physical memory layout. //! //! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used //! as the boot core's stack. //! //! +---------------------------------------+ //! | | boot_core_stack_start @ 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | data_start == code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | data_end_exclusive //! | | //! //! //! //! //! //! The virtual memory layout is as follows: //! //! +---------------------------------------+ //! | | boot_core_stack_start @ 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | data_start == code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | mmio_remap_start == data_end_exclusive //! | VA region for MMIO remapping | //! | | //! +---------------------------------------+ //! | | mmio_remap_end_exclusive //! | | pub mod mmu; use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // Symbols from the linker script. extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; static __data_start: UnsafeCell<()>; static __data_end_exclusive: UnsafeCell<()>; static __mmio_remap_start: UnsafeCell<()>; static __mmio_remap_end_exclusive: UnsafeCell<()>; static __boot_core_stack_start: UnsafeCell<()>; static __boot_core_stack_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { use super::*; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); pub const PERIPHERAL_IC_SIZE: usize = 0x24; pub const GPIO_START: Address = Address::new(0x3F20_0000); pub const GPIO_SIZE: usize = 0xA0; pub const PL011_UART_START: Address = Address::new(0x3F20_1000); pub const PL011_UART_SIZE: usize = 0x48; pub const END: Address = Address::new(0x4001_0000); } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const GPIO_START: Address = Address::new(0xFE20_0000); pub const GPIO_SIZE: usize = 0xA0; pub const PL011_UART_START: Address = Address::new(0xFE20_1000); pub const PL011_UART_SIZE: usize = 0x48; pub const GICD_START: Address = Address::new(0xFF84_1000); pub const GICD_SIZE: usize = 0x824; pub const GICC_START: Address = Address::new(0xFF84_2000); pub const GICC_SIZE: usize = 0x14; pub const END: Address = Address::new(0xFF85_0000); } pub const END: Address = mmio::END; } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Start page address of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn virt_code_start() -> PageAddress { PageAddress::from(unsafe { __code_start.get() as usize }) } /// Size of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_size() -> usize { unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } } /// Start page address of the data segment. #[inline(always)] fn virt_data_start() -> PageAddress { PageAddress::from(unsafe { __data_start.get() as usize }) } /// Size of the data segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn data_size() -> usize { unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } } /// Start page address of the MMIO remap reservation. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn virt_mmio_remap_start() -> PageAddress { PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) } /// Size of the MMIO remap reservation. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn mmio_remap_size() -> usize { unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } } /// Start page address of the boot core's stack. #[inline(always)] fn virt_boot_core_stack_start() -> PageAddress { PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) } /// Size of the boot core's stack. #[inline(always)] fn boot_core_stack_size() -> usize { unsafe { (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Exclusive end address of the physical address space. #[inline(always)] pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { PageAddress::from(map::END) } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs ================================================ // 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() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. #![feature(format_args_nl)] #![no_main] #![no_std] use libkernel::{bsp, cpu, driver, exception, info, memory, state, time}; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order: /// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, /// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ /// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { Err(string) => panic!("Error mapping kernel binary: {}", string), Ok(addr) => addr, }; if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { panic!("Enabling MMU failed: {}", e); } memory::mmu::post_enable_init(); // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers_and_irqs(); // Unmask interrupts on the boot CPU core. exception::asynchronous::local_irq_unmask(); // Announce conclusion of the kernel_init() phase. state::state_manager().transition_to_single_core_main(); // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { info!("{}", libkernel::version()); info!("Booting on: {}", bsp::board_name()); info!("MMU online:"); memory::mmu::kernel_print_mappings(); let (_, privilege_level) = exception::current_privilege_level(); info!("Current privilege level: {}", privilege_level); info!("Exception handling state:"); exception::asynchronous::print_state(); info!( "Architectural timer resolution: {} ns", time::time_manager().resolution().as_nanos() ); info!("Drivers loaded:"); driver::driver_manager().enumerate(); info!("Registered IRQ handlers:"); exception::asynchronous::irq_manager().print_handler(); info!("Echoing input now"); cpu::wait_forever(); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/mapping_record.rs ================================================ // 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()); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/page_alloc.rs ================================================ // 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) } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Translation table. #[cfg(target_arch = "aarch64")] #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] mod arch_translation_table; use super::{AttributeFields, MemoryRegion}; use crate::memory::{Address, Physical, Virtual}; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- #[cfg(target_arch = "aarch64")] pub use arch_translation_table::FixedSizeTranslationTable; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Translation table interfaces. pub mod interface { use super::*; /// Translation table operations. pub trait TranslationTable { /// Anything that needs to run before any of the other provided functions can be used. /// /// # Safety /// /// - Implementor must ensure that this function can run only once or is harmless if invoked /// multiple times. fn init(&mut self); /// The translation table's base address to be used for programming the MMU. fn phys_base_address(&self) -> Address; /// Map the given virtual memory region to the given physical memory region. /// /// # Safety /// /// - Using wrong attributes can cause multiple issues of different nature in the system. /// - It is not required that the architectural implementation prevents aliasing. That is, /// mapping to the same physical memory using multiple virtual addresses, which would /// break Rust's ownership assumptions. This should be protected against in the kernel's /// generic MMU code. unsafe fn map_at( &mut self, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str>; } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; use arch_translation_table::MinSizeTranslationTable; use interface::TranslationTable; use test_macros::kernel_test; /// Sanity checks for the TranslationTable implementation. #[kernel_test] fn translationtable_implementation_sanity() { // This will occupy a lot of space on the stack. let mut tables = MinSizeTranslationTable::new(); tables.init(); let virt_start_page_addr: PageAddress = PageAddress::from(0); let virt_end_exclusive_page_addr: PageAddress = virt_start_page_addr.checked_offset(5).unwrap(); let phys_start_page_addr: PageAddress = PageAddress::from(0); let phys_end_exclusive_page_addr: PageAddress = phys_start_page_addr.checked_offset(5).unwrap(); let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); let attr = AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }; unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/types.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit types. use crate::{ bsp, common, memory::{Address, AddressType, Physical}, }; use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// A wrapper type around [Address] that ensures page alignment. #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct PageAddress { inner: Address, } /// A type that describes a region of memory in quantities of pages. #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct MemoryRegion { start: PageAddress, end_exclusive: PageAddress, } /// Architecture agnostic memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum MemAttributes { CacheableDRAM, Device, } /// Architecture agnostic access permissions. #[allow(missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum AccessPermissions { ReadOnly, ReadWrite, } /// Collection of memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, pub execute_never: bool, } /// An MMIO descriptor for use in device drivers. #[derive(Copy, Clone)] pub struct MMIODescriptor { start_addr: Address, end_addr_exclusive: Address, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------ // PageAddress //------------------------------------------------------------------------------ impl PageAddress { /// Unwraps the value. pub fn into_inner(self) -> Address { self.inner } /// Calculates the offset from the page address. /// /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * /// page_size`. pub fn checked_offset(self, count: isize) -> Option { if count == 0 { return Some(self); } let delta = count .unsigned_abs() .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; let result = if count.is_positive() { self.inner.as_usize().checked_add(delta)? } else { self.inner.as_usize().checked_sub(delta)? }; Some(Self { inner: Address::new(result), }) } } impl From for PageAddress { fn from(addr: usize) -> Self { assert!( common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), "Input usize not page aligned" ); Self { inner: Address::new(addr), } } } impl From> for PageAddress { fn from(addr: Address) -> Self { assert!(addr.is_page_aligned(), "Input Address not page aligned"); Self { inner: addr } } } impl Step for PageAddress { fn steps_between(start: &Self, end: &Self) -> Option { if start > end { return None; } // Since start <= end, do unchecked arithmetic. Some( (end.inner.as_usize() - start.inner.as_usize()) >> bsp::memory::mmu::KernelGranule::SHIFT, ) } fn forward_checked(start: Self, count: usize) -> Option { start.checked_offset(count as isize) } fn backward_checked(start: Self, count: usize) -> Option { start.checked_offset(-(count as isize)) } } //------------------------------------------------------------------------------ // MemoryRegion //------------------------------------------------------------------------------ impl MemoryRegion { /// Create an instance. pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { assert!(start <= end_exclusive); Self { start, end_exclusive, } } fn as_range(&self) -> Range> { self.into_iter() } /// Returns the start page address. pub fn start_page_addr(&self) -> PageAddress { self.start } /// Returns the start address. pub fn start_addr(&self) -> Address { self.start.into_inner() } /// Returns the exclusive end page address. pub fn end_exclusive_page_addr(&self) -> PageAddress { self.end_exclusive } /// Returns the exclusive end page address. pub fn end_inclusive_page_addr(&self) -> PageAddress { self.end_exclusive.checked_offset(-1).unwrap() } /// Checks if self contains an address. pub fn contains(&self, addr: Address) -> bool { let page_addr = PageAddress::from(addr.align_down_page()); self.as_range().contains(&page_addr) } /// Checks if there is an overlap with another memory region. pub fn overlaps(&self, other_region: &Self) -> bool { let self_range = self.as_range(); self_range.contains(&other_region.start_page_addr()) || self_range.contains(&other_region.end_inclusive_page_addr()) } /// Returns the number of pages contained in this region. pub fn num_pages(&self) -> usize { PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() } /// Returns the size in bytes of this region. pub fn size(&self) -> usize { // Invariant: start <= end_exclusive, so do unchecked arithmetic. let end_exclusive = self.end_exclusive.into_inner().as_usize(); let start = self.start.into_inner().as_usize(); end_exclusive - start } /// Splits the MemoryRegion like: /// /// -------------------------------------------------------------------------------- /// | | | | | | | | | | | | | | | | | | | /// -------------------------------------------------------------------------------- /// ^ ^ ^ /// | | | /// left_start left_end_exclusive | /// | /// ^ | /// | | /// right_start right_end_exclusive /// /// Left region is returned to the caller. Right region is the new region for this struct. pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { let count: usize = num_pages.into(); let left_end_exclusive = self.start.checked_offset(count as isize); let left_end_exclusive = match left_end_exclusive { None => return Err("Overflow while calculating left_end_exclusive"), Some(x) => x, }; if left_end_exclusive > self.end_exclusive { return Err("Not enough free pages"); } let allocation = Self { start: self.start, end_exclusive: left_end_exclusive, }; self.start = left_end_exclusive; Ok(allocation) } } impl IntoIterator for MemoryRegion { type Item = PageAddress; type IntoIter = Range; fn into_iter(self) -> Self::IntoIter { Range { start: self.start, end: self.end_exclusive, } } } impl From for MemoryRegion { fn from(desc: MMIODescriptor) -> Self { let start = PageAddress::from(desc.start_addr.align_down_page()); let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); Self { start, end_exclusive, } } } //------------------------------------------------------------------------------ // MMIODescriptor //------------------------------------------------------------------------------ impl MMIODescriptor { /// Create an instance. pub const fn new(start_addr: Address, size: usize) -> Self { assert!(size > 0); let end_addr_exclusive = Address::new(start_addr.as_usize() + size); Self { start_addr, end_addr_exclusive, } } /// Return the start address. pub const fn start_addr(&self) -> Address { self.start_addr } /// Return the exclusive end address. pub fn end_addr_exclusive(&self) -> Address { self.end_addr_exclusive } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use crate::memory::Virtual; use test_macros::kernel_test; /// Sanity of [PageAddress] methods. #[kernel_test] fn pageaddress_type_method_sanity() { let page_addr: PageAddress = PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); assert_eq!( page_addr.checked_offset(-2), Some(PageAddress::::from(0)) ); assert_eq!( page_addr.checked_offset(2), Some(PageAddress::::from( bsp::memory::mmu::KernelGranule::SIZE * 4 )) ); assert_eq!( PageAddress::::from(0).checked_offset(0), Some(PageAddress::::from(0)) ); assert_eq!(PageAddress::::from(0).checked_offset(-1), None); let max_page_addr = Address::::new(usize::MAX).align_down_page(); assert_eq!( PageAddress::::from(max_page_addr).checked_offset(1), None ); let zero = PageAddress::::from(0); let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); } /// Sanity of [MemoryRegion] methods. #[kernel_test] fn memoryregion_type_method_sanity() { let zero = PageAddress::::from(0); let zero_region = MemoryRegion::new(zero, zero); assert_eq!(zero_region.num_pages(), 0); assert_eq!(zero_region.size(), 0); let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); let one_region = MemoryRegion::new(zero, one); assert_eq!(one_region.num_pages(), 1); assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); let mut three_region = MemoryRegion::new(zero, three); assert!(three_region.contains(zero.into_inner())); assert!(!three_region.contains(three.into_inner())); assert!(three_region.overlaps(&one_region)); let allocation = three_region .take_first_n_pages(NonZeroUsize::new(2).unwrap()) .unwrap(); assert_eq!(allocation.num_pages(), 2); assert_eq!(three_region.num_pages(), 1); for (i, alloc) in allocation.into_iter().enumerate() { assert_eq!( alloc.into_inner().as_usize(), i * bsp::memory::mmu::KernelGranule::SIZE ); } } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; mod mapping_record; mod page_alloc; mod translation_table; mod types; use crate::{ bsp, memory::{Address, Physical, Virtual}, synchronization, warn, }; use core::{fmt, num::NonZeroUsize}; pub use types::*; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// MMU enable errors variants. #[allow(missing_docs)] #[derive(Debug)] pub enum MMUEnableError { AlreadyEnabled, Other(&'static str), } /// Memory Management interfaces. pub mod interface { use super::*; /// MMU functions. pub trait MMU { /// Turns on the MMU for the first time and enables data and instruction caching. /// /// # Safety /// /// - Changes the HW's global state. unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError>; /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; } } /// Describes the characteristics of a translation granule. pub struct TranslationGranule; /// Describes properties of an address space. pub struct AddressSpace; /// Intended to be implemented for [`AddressSpace`]. pub trait AssociatedTranslationTable { /// A translation table whose address range is: /// /// [AS_SIZE - 1, 0] type TableStartFromBottom; } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- use interface::MMU; use synchronization::interface::*; use translation_table::interface::TranslationTable; /// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's /// MMIO VA allocator with it. fn kernel_init_mmio_va_allocator() { let region = bsp::memory::mmu::virt_mmio_remap_region(); page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); } /// Map a region in the kernel's translation tables. /// /// No input checks done, input is passed through to the architectural implementation. /// /// # Safety /// /// - See `map_at()`. /// - Does not prevent aliasing. unsafe fn kernel_map_at_unchecked( name: &'static str, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str> { bsp::memory::mmu::kernel_translation_tables() .write(|tables| tables.map_at(virt_region, phys_region, attr))?; if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { warn!("{}", x); } Ok(()) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl fmt::Display for MMUEnableError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), MMUEnableError::Other(x) => write!(f, "{}", x), } } } impl TranslationGranule { /// The granule's size. pub const SIZE: usize = Self::size_checked(); /// The granule's mask. pub const MASK: usize = Self::SIZE - 1; /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(GRANULE_SIZE.is_power_of_two()); GRANULE_SIZE } } impl AddressSpace { /// The address space size. pub const SIZE: usize = Self::size_checked(); /// The address space shift, aka log2(size). pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(AS_SIZE.is_power_of_two()); // Check for architectural restrictions as well. Self::arch_address_space_size_sanity_checks(); AS_SIZE } } /// Raw mapping of a virtual to physical region in the kernel translation tables. /// /// Prevents mapping into the MMIO range of the tables. /// /// # Safety /// /// - See `kernel_map_at_unchecked()`. /// - Does not prevent aliasing. Currently, the callers must be trusted. pub unsafe fn kernel_map_at( name: &'static str, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str> { if bsp::memory::mmu::virt_mmio_remap_region().overlaps(virt_region) { return Err("Attempt to manually map into MMIO region"); } kernel_map_at_unchecked(name, virt_region, phys_region, attr)?; Ok(()) } /// MMIO remapping in the kernel translation tables. /// /// Typically used by device drivers. /// /// # Safety /// /// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. pub unsafe fn kernel_map_mmio( name: &'static str, mmio_descriptor: &MMIODescriptor, ) -> Result, &'static str> { let phys_region = MemoryRegion::from(*mmio_descriptor); let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); // Check if an identical region has been mapped for another driver. If so, reuse it. let virt_addr = if let Some(addr) = mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) { addr // Otherwise, allocate a new region and map it. } else { let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { None => return Err("Requested 0 pages"), Some(x) => x, }; let virt_region = page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; kernel_map_at_unchecked( name, &virt_region, &phys_region, &AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, )?; virt_region.start_addr() }; Ok(virt_addr + offset_into_start_page) } /// Map the kernel's binary. Returns the translation table's base address. /// /// # Safety /// /// - See [`bsp::memory::mmu::kernel_map_binary()`]. pub unsafe fn kernel_map_binary() -> Result, &'static str> { let phys_kernel_tables_base_addr = bsp::memory::mmu::kernel_translation_tables().write(|tables| { tables.init(); tables.phys_base_address() }); bsp::memory::mmu::kernel_map_binary()?; Ok(phys_kernel_tables_base_addr) } /// Enable the MMU and data + instruction caching. /// /// # Safety /// /// - Crucial function during kernel init. Changes the the complete memory view of the processor. pub unsafe fn enable_mmu_and_caching( phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError> { arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) } /// Finish initialization of the MMU subsystem. pub fn post_enable_init() { kernel_init_mmio_va_allocator(); } /// Human-readable print of all recorded kernel mappings. pub fn kernel_print_mappings() { mapping_record::kernel_print() } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; use test_macros::kernel_test; /// Check that you cannot map into the MMIO VA range from kernel_map_at(). #[kernel_test] fn no_manual_mmio_map() { let phys_start_page_addr: PageAddress = PageAddress::from(0); let phys_end_exclusive_page_addr: PageAddress = phys_start_page_addr.checked_offset(5).unwrap(); let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); let num_pages = NonZeroUsize::new(phys_region.num_pages()).unwrap(); let virt_region = page_alloc::kernel_mmio_va_allocator() .lock(|allocator| allocator.alloc(num_pages)) .unwrap(); let attr = AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }; unsafe { assert_eq!( kernel_map_at("test", &virt_region, &phys_region, &attr), Err("Attempt to manually map into MMIO region") ) }; } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management. pub mod mmu; use crate::{bsp, common}; use core::{ fmt, marker::PhantomData, ops::{Add, Sub}, }; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Metadata trait for marking the type of an address. pub trait AddressType: Copy + Clone + PartialOrd + PartialEq + Ord + Eq {} /// Zero-sized type to mark a physical address. #[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub enum Physical {} /// Zero-sized type to mark a virtual address. #[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub enum Virtual {} /// Generic address type. #[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub struct Address { value: usize, _address_type: PhantomData ATYPE>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl AddressType for Physical {} impl AddressType for Virtual {} impl Address { /// Create an instance. pub const fn new(value: usize) -> Self { Self { value, _address_type: PhantomData, } } /// Convert to usize. pub const fn as_usize(self) -> usize { self.value } /// Align down to page size. #[must_use] pub const fn align_down_page(self) -> Self { let aligned = common::align_down(self.value, bsp::memory::mmu::KernelGranule::SIZE); Self::new(aligned) } /// Align up to page size. #[must_use] pub const fn align_up_page(self) -> Self { let aligned = common::align_up(self.value, bsp::memory::mmu::KernelGranule::SIZE); Self::new(aligned) } /// Checks if the address is page aligned. pub const fn is_page_aligned(&self) -> bool { common::is_aligned(self.value, bsp::memory::mmu::KernelGranule::SIZE) } /// Return the address' offset into the corresponding page. pub const fn offset_into_page(&self) -> usize { self.value & bsp::memory::mmu::KernelGranule::MASK } } impl Add for Address { type Output = Self; #[inline(always)] fn add(self, rhs: usize) -> Self::Output { match self.value.checked_add(rhs) { None => panic!("Overflow on Address::add"), Some(x) => Self::new(x), } } } impl Sub> for Address { type Output = Self; #[inline(always)] fn sub(self, rhs: Address) -> Self::Output { match self.value.checked_sub(rhs.value) { None => panic!("Overflow on Address::sub"), Some(x) => Self::new(x), } } } impl fmt::Display for Address { // Don't expect to see physical addresses greater than 40 bit. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let q3: u8 = ((self.value >> 32) & 0xff) as u8; let q2: u16 = ((self.value >> 16) & 0xffff) as u16; let q1: u16 = (self.value & 0xffff) as u16; write!(f, "0x")?; write!(f, "{:02x}_", q3)?; write!(f, "{:04x}_", q2)?; write!(f, "{:04x}", q1) } } impl fmt::Display for Address { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let q4: u16 = ((self.value >> 48) & 0xffff) as u16; let q3: u16 = ((self.value >> 32) & 0xffff) as u16; let q2: u16 = ((self.value >> 16) & 0xffff) as u16; let q1: u16 = (self.value & 0xffff) as u16; write!(f, "0x")?; write!(f, "{:04x}_", q4)?; write!(f, "{:04x}_", q3)?; write!(f, "{:04x}_", q2)?; write!(f, "{:04x}", q1) } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Sanity of [Address] methods. #[kernel_test] fn address_type_method_sanity() { let addr = Address::::new(bsp::memory::mmu::KernelGranule::SIZE + 100); assert_eq!( addr.align_down_page().as_usize(), bsp::memory::mmu::KernelGranule::SIZE ); assert_eq!( addr.align_up_page().as_usize(), bsp::memory::mmu::KernelGranule::SIZE * 2 ); assert!(!addr.is_page_aligned()); assert_eq!(addr.offset_into_page(), 100); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs ================================================ // 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(); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Timer sanity tests. #![feature(custom_test_frameworks)] #![no_main] #![no_std] #![reexport_test_harness_main = "test_main"] #![test_runner(libkernel::test_runner)] use core::time::Duration; use libkernel::{bsp, cpu, exception, memory, time}; use test_macros::kernel_test; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { Err(string) => panic!("Error mapping kernel binary: {}", string), Ok(addr) => addr, }; if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { panic!("Enabling MMU failed: {}", e); } memory::mmu::post_enable_init(); bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. test_main(); cpu::qemu_exit_success() } /// Simple check that the timer is running. #[kernel_test] fn timer_is_counting() { assert!(time::time_manager().uptime().as_nanos() > 0) } /// Timer resolution must be sufficient. #[kernel_test] fn timer_resolution_is_sufficient() { assert!(time::time_manager().resolution().as_nanos() > 0); assert!(time::time_manager().resolution().as_nanos() < 100) } /// Sanity check spin_for() implementation. #[kernel_test] fn spin_accuracy_check_1_second() { let t1 = time::time_manager().uptime(); time::time_manager().spin_for(Duration::from_secs(1)); let t2 = time::time_manager().uptime(); assert_eq!((t2 - t1).as_secs(), 1) } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. #![feature(format_args_nl)] #![no_main] #![no_std] /// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. /// /// In this test, reaching the panic is a success, because it is called from the synchronous /// exception handler, which is what this test wants to achieve. /// /// It also means that this integration test can not use any other code that calls panic!() directly /// or indirectly. mod panic_exit_success; use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { Err(string) => { info!("Error mapping kernel binary: {}", string); cpu::qemu_exit_failure() } Ok(addr) => addr, }; if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } memory::mmu::post_enable_init(); bsp::driver::qemu_bring_up_console(); info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); // If execution reaches here, the memory access above did not cause a page fault exception. cpu::qemu_exit_failure() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2022-2023 Andre Richter //! A simple sanity test to see if exception restore code works. #![feature(format_args_nl)] #![no_main] #![no_std] /// Console tests should time out on the I/O harness in case of panic. mod panic_wait_forever; use core::arch::asm; use libkernel::{bsp, cpu, exception, info, memory, println}; #[inline(never)] fn nested_system_call() { #[cfg(target_arch = "aarch64")] unsafe { asm!("svc #0x1337", options(nomem, nostack, preserves_flags)); } #[cfg(not(target_arch = "aarch64"))] { info!("Not supported yet"); cpu::wait_forever(); } } #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); // This line will be printed as the test header. println!("Testing exception restore"); let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { Err(string) => { info!("Error mapping kernel binary: {}", string); cpu::qemu_exit_failure() } Ok(addr) => addr, }; if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { info!("Enabling MMU failed: {}", e); cpu::qemu_exit_failure() } memory::mmu::post_enable_init(); bsp::driver::qemu_bring_up_console(); info!("Making a dummy system call"); // Calling this inside a function indirectly tests if the link register is restored properly. nested_system_call(); info!("Back from system call!"); // The QEMU process running this test will be closed by the I/O test harness. cpu::wait_forever(); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs ================================================ // 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()); } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 14_virtual_mem_part2_mmio_remap/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 14_virtual_mem_part2_mmio_remap/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel" ] [profile.release] lto = true ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 # Optional integration test name. ifdef TEST TEST_ARG = --test $(TEST) else TEST_ARG = --test '*' endif ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = kernel/Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF_RAW = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Translation tables ##------------------------------------------------------------------------------ TT_TOOL_PATH = tools/translation_table_tool KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) KERNEL_ELF = $(KERNEL_ELF_TTABLES) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Precompute the kernel translation tables and patch them into the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF_TTABLES) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot test_unit test_integration test_unit test_integration: FEATURES += --features test_build ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test_unit test_integration test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER #!/usr/bin/env bash # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure # this script executes from the root. cd $(shell pwd) TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY endef export KERNEL_TEST_RUNNER define test_prepare @mkdir -p target @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh @chmod +x target/kernel_test_runner.sh endef ##------------------------------------------------------------------------------ ## Run unit test(s) ##------------------------------------------------------------------------------ test_unit: $(call color_header, "Compiling unit test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib ##------------------------------------------------------------------------------ ## Run integration test(s) ##------------------------------------------------------------------------------ test_integration: $(call color_header, "Compiling integration test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) test: test_boot test_unit test_integration endif ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/README.md ================================================ # Tutorial 15 - Virtual Memory Part 3: Precomputed Translation Tables ## tl;dr - We are making the next baby-steps towards mapping the kernel to the most significant area of the virtual memory space. - Instead of dynamically computing the kernel's translation tables during runtime while booting, we are precomputing them in advance just after kernel compilation, and patch them into the kernel's binary ahead of time. - For now, we are still `identity-mapping` the kernel binary. - However, after this tutorial, we have all the infrastructure in place to easily map it elsewhere. ## Table of Contents - [Introduction](#introduction) - [When Load Address != Link Address, Funny Things Can Happen](#when-load-address--link-address-funny-things-can-happen) * [Interim Conclusion](#interim-conclusion) * [Doing the Same Thing - Expecting Different Results](#doing-the-same-thing---expecting-different-results) - [Position-Independent Code (PIC)](#position-independent-code-pic) * [Using PIC during kernel startup](#using-pic-during-kernel-startup) - [Precomputed Translation Tables](#precomputed-translation-tables) - [Implementation](#implementation) * [Preparing the Kernel Tables](#preparing-the-kernel-tables) * [Turning on the MMU Before Switching to EL1](#turning-on-the-mmu-before-switching-to-el1) * [The Translation Table Tool](#the-translation-table-tool) * [Other changes](#other-changes) - [Discussion](#discussion) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction This tutorial is another preparatory step for our overall goal of mapping the kernel to the most significant area of the virtual memory space. The reasoning of why we want to do this was given in the previous tutorial's introduction. But lets for a quick moment think about what it actually means in practice: Currently, the kernel's binary is loaded by the Raspberry's firmware at address `0x8_0000`. In decimal, this address is at `512 KiB`, and therefore well within the _least significant part_ of the address space. Let's have a look at the picture from the [ARM Cortex-A Series Programmer’s Guide for ARMv8-A] again to understand in which virtual address space region the kernel would ideally be mapped to:

As we can see, the architecture proposes somewhere between addresses `0xffff_0000_0000_0000` and `0xffff_ffff_ffff_ffff`. Once we succeed in mapping the kernel there, the whole lower range between `0x0` and `0xffff_ffff_ffff` would be free for future applications to use. [ARM Cortex-A Series Programmer’s Guide for ARMv8-A]: https://developer.arm.com/documentation/den0024/latest/ Now, how can we get there? ## When Load Address != Link Address, Funny Things Can Happen Imagine that, using the linker script, we link the kernel so that its `_start()` function is located at address `0xffff_0000_0000_0000`. What hasn't changed is that the Raspberry's firmware will still load the kernel binary at address `0x8_0000`, and the kernel will still start executing from there with the `MMU` disabled. So one of the very first things the kernel must achieve during its boot to function correctly, is to somehow enable the `MMU` together with `translation tables` that account for the address offset (`0xffff_0000_0000_0000 -> 0x8_0000`). In previous tutorials, we already generated translation tables during the kernel's boot, so lets quickly remember how we did that: In `src/bsp/__board_name__/memory/mmu.rs` we have a static (or "global" in non-Rust speak) instance of `struct KernelTranslationTable`: ```rust static KERNEL_TABLES: InitStateLock = InitStateLock::new(KernelTranslationTable::new()); ``` In other parts of the kernel code, this instance would be referenced one way or the other, and its member functions would be called, for example, when mapping a range of pages. At the end of the day, after multiple layers of indirection, what happens at the most basic level is that a `piece of code` manipulates some `global data`. So part of the job of the code is to retrieve the data's constant address before it can manipulate it. Let's simplify the address-retrieval to the most basic code example possible. The example will be presented as `C` code. Don't ask yet why `C` is chosen. It will get clear as the tutorial develops. ```c #include uint64_t global_data_word = 0x11223344; uint64_t* get_address_of_global(void) { return &global_data_word; } ``` Let's compile and link this using the following linker script: ```ld.s SECTIONS { . = 0x80000; .text : { QUAD(0); /* Intentional fill word */ QUAD(0); /* Intentional fill word */ KEEP(*(.text*)) } .got : ALIGN(8) { *(.got) } .data : ALIGN(64K) { QUAD(0); /* Intentional fill word */ *(.data*) } } ``` Here are the compilation steps and the corresponding `objdump` for `AArch64`: ```console $ clang --target=aarch64-none-elf -Iinclude -Wall -c start.c -o start.o $ ld.lld start.o -T kernel.ld -o example.elf ``` ```c-objdump Disassembly of section .text: 0000000000080010 get_address_of_global: 80010: 80 00 00 90 adrp x0, #0x10000 80014: 00 20 00 91 add x0, x0, #0x8 80018: c0 03 5f d6 ret Disassembly of section .data: 0000000000090008 global_data_word: 90008: 44 33 22 11 9000c: 00 00 00 00 ``` As you can see, the address of function `get_address_of_global()` is `0x8_0010` and `global_data_word` got address `0x9_0008`. In the function body, the compiler emitted an [`ADRP`] and `ADD` instruction pair, which means that the global's address is calculated as a `PC-relative offset`. `PC` means program counter, aka the current position of where the CPU core is currently executing from. Without going in too much detail, what the instruction basically does is: It retrieves the `4 KiB` page address that belongs to the program counter's (PC) current position (PC is at `0x8_0010`, so the page address is `0x8_0000`), and adds `0x1_0000`. So after the `ADRP` instruction, register `x0` holds the value `0x9_0000`. To this value, `8` is added in the next instruction, resulting in the overall address of `0x9_0008`, which is exactly where `global_data_word` is located. This works, because after linking a `static executable binary` like we do since `tutorial 01`, relative positions of code and data are fixed, and not supposed to change during runtime. [`ADRP`]: https://developer.arm.com/documentation/dui0802/b/A64-General-Instructions/ADRP If the Raspberry's firmware now loads this binary at address `0x8_0000`, as always, we can be sure that our function returns the correct address of our global data word. Now lets link this to the most significant area of memory: ```ld.s SECTIONS { . = 0xffff000000000000; /* <--- Only line changed in the linker script! */ .text : { /* omitted for brevity */ } ``` And compile again: ```c-objdump Disassembly of section .text: ffff000000000010 get_address_of_global: ffff000000000010: 80 00 00 90 adrp x0, #0x10000 ffff000000000014: 00 20 00 91 add x0, x0, #0x8 ffff000000000018: c0 03 5f d6 ret Disassembly of section .data: ffff000000010008 global_data_word: ffff000000010008: 44 33 22 11 ffff00000001000c: 00 00 00 00 ``` And let the Raspberry's firmware load the binary at address `0x8_0000` again (we couldn't load it to `0xffff_0000_0000_0000` even if we wanted to. That address is `15 Exbibyte`. A Raspberry Pi with that much RAM won't exist for some time to come 😉). Let's try to answer the same question again: Would `get_address_of_global()` return the value for `global_data_word` that we expect to see (`0xffff_0000_0001_0008` as shown in the objdump)? This time, the answer is **no**. It would again return `0x9_0008`. Why is that? Don't let yourself be distracted by the addresses the `objdump` above is showing. When the Raspberry's firmware loads this binary at `0x8_0000`, then the Program Counter value when `get_address_of_global()` executes is again `0x8_0010`. So **the PC-relative calculation** will not result in the expected value, which would be the **absolute** (alternatively: **link-time**) address of `global_data_word`. ### Interim Conclusion What have we learned so far? We wrote a little piece of code in a high-level language that retrieves an address, and we naively expected to retrieve an **absolute** address. But compiler and linker conspired against us, and machine code was emitted that uses a PC-relative addressing scheme, so our expectation is not matched when **load address != link address**. If you compile for `AArch64`, you'll see relative addressing schemes a lot, because it is natural to the architecture. If you now say: Wait a second, how is this a problem? It actually helps! After all, since the code is loaded at address `0x8_0000`, this relative addressing scheme will ensure that the processor accesses the global data word at the correct address! Yes, in this particular, constrained demo case, it worked out for us. But have a look at the following. ### Doing the Same Thing - Expecting Different Results Let's take a quick detour and see what happens if we compile **the exactly same code** for the `x86_64` processor architecture. First when linked to `0x8_0000`: ```c-objdump Disassembly of section .text: 0000000000080070 get_address_of_global: 80070: 55 push rbp 80071: 48 89 e5 mov rbp, rsp 80074: 48 b8 08 00 09 00 00 00 00 00 movabs rax, 0x90008 8007e: 5d pop rbp 8007f: c3 ret Disassembly of section .data: ffff000000010008 global_data_word: ffff000000010008: 44 33 22 11 ffff00000001000c: 00 00 00 00 ``` And now linked to `0xffff_0000_0000_0000`: ```c-objdump Disassembly of section .text: ffff000000000070 get_address_of_global: ffff000000000070: 55 push rbp ffff000000000071: 48 89 e5 mov rbp, rsp ffff000000000074: 48 b8 08 00 01 00 00 00 ff ff movabs rax, 0xffff000000010008 ffff00000000007e: 5d pop rbp ffff00000000007f: c3 ret Disassembly of section .data: ffff000000010008 global_data_word: ffff000000010008: 44 33 22 11 ffff00000001000c: 00 00 00 00 ``` Both times, the `movabs` instruction gets emitted. It means that the address is put into the target register using hardcoded `immediate values`. PC-relative address calculation is not used here. Hence, this code would return the `absolute` address in both cases. Which means in the second case, even when the binary would be loaded at `0x8_0000`, the return value would be `0xffff_0000_0001_0008`. **In summary, we get a different result for the same piece of `C` code, depending on the target processor architecture**. What do we learn from this little detour? First, you cannot naively compile and run `Rust` or `C` statically linked binaries when there will be a **load address != link address** situation. You'll run into undefined behavior very fast. It is kinda expected and obvious, but hopefully it helped to see it fail in action. Furthermore, it is important to understand that there are of course ways to load a symbol's absolute address into `AArch64` registers using `immediate values` as well. Likewise, you can also do PC-relative addressing in `x86`. We just looked at a tiny example. Maybe the next line of code would be compiled into the opposite behavior on the two architectures, so that the `x86` code would do a PC-relative calculation while the `AArch64` code goes for absolute. At the end of the day, what is needed to solve our task at hand (bringup of virtual memory, while being linked to one address and executing from another), is tight control over the machine instructions that get emitted for **those pieces of code** that generate the `translation tables` and enable the `MMU`. What we need is called [position-independent code]. [position-independent code]: https://en.wikipedia.org/wiki/Position-independent_code > Much low-level stuff in this tutorial, isn't it? This was a lot to digest already, but we're far > from finished. So take a minute or two and clear your mind before we continue. 🧘 ## Position-Independent Code (PIC) As describend by Wikipedia, position-independent code > is a body of machine code that, being placed somewhere in the primary memory, **executes > properly** regardless of its absolute address. Your safest bet is to write the pieces that need to be position-independent in `assembly`, because this gives you full control over when relative or absolute addresses are being generated or used. You will see this approach often in big projects like the Linux kernel, for example. The downside of that approach is that the programmer needs good domain knowledge. If you feel more adventurous and don't want to go completely without high-level code, you can try to make use of suitable compiler flags such as `-fpic`, and only use `assembly` where absolutely needed. Here is the [`-fpic` description for GCC]: > -fpic > > Generate position-independent code (PIC) suitable for use in a shared library, if supported for > the target machine. Such code accesses all constant addresses through a global offset table (GOT). > The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not > part of GCC; it is part of the operating system). [`-fpic` description for GCC]: https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#Code-Gen-Options However, it is very important to understand that this flag **is not** a ready-made solution for our particular problem (and wasn't invented for that case either). There is a hint in the quoted text above that gives it away: "_The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC; it is part of the operating system)_". Well, we are a booting kernel, and not some (userspace) program running on top of an operating system. Hence, there is no dynamic loader available. However, it is still possible to benefit from `-fpic` even in our case. Lets have a look at what happens if we compile the earlier piece of `C` code for `AArch64` using `-fpic`, still linking the output to the most signifcant part of the memory space: ```console $ clang --target=aarch64-none-elf -Iinclude -Wall -fpic -c start.c -o start.o $ ld.lld start.o -T kernel.ld -o example.elf ``` ```c-objdump Disassembly of section .text: ffff000000000010 get_address_of_global: ffff000000000010: 00 00 00 90 adrp x0, #0x0 ffff000000000014: 00 28 40 f9 ldr x0, [x0, #0x50] ffff000000000018: c0 03 5f d6 ret Disassembly of section .got: ffff000000000050 .got: ffff000000000050: 08 00 01 00 ffff000000000054: 00 00 ff ff Disassembly of section .data: ffff000000010008 global_data_word: ffff000000010008: 44 33 22 11 ffff00000001000c: 00 00 00 00 ``` What changed compared to earlier is that `get_address_of_global()` now indirects through the `Global Offset Table`, as has been promised by the compiler's documentation. Specifically, `get_address_of_global()` addresses the `GOT` using PC-relative addressing (distance from code to `GOT` must always be fixed), and loads the first 64 bit word from the start of the `GOT`, which happens to be `0xffff_0000_0001_0008`. Okay okay okay... So when we use `-fpic`, we get the **absolute** address of `global_data_word` even on `AArch64` now. How does this help when the code executes from `0x8_0000`? Well, this is the part where the `dynamic loader` quoted above would come into picture if this was a userspace program: "_The dynamic loader resolves the GOT entries when the program starts_". The `-fpic` flag is normally used to compile _shared libraries_. Suppose we have a program that uses one or more shared library. For various reasons, it happens that the shared library is loaded at a different address than where the userspace program would initially expect it. In our example, `global_data_word` could be supplied by such a shared library, and the userspace program is only referencing it. The dynamic loader would know where the shared library was loaded into memory, and therefore know the real address of `global_data_word`. So before the userspace program starts, the loader would overwrite the `GOT` entry with the correct location. Et voilà, the compiled high-level code would execute properly. ### Using PIC during kernel startup If you think about it, our problem is a special case of what we just learned. We have a single statically linked binary, where everything is dislocated by a fixed offset. In our case, it is `0xffff_0000_0000_0000 - 0x8_0000 = 0x0fff_efff_ffff8_0000`. If we write some PIC-`assembly` code which loops over the `GOT` and subtracts `0x0fff_efff_ffff8_0000` from every entry as the very first thing when our kernel boots, any high-level code compiled with `-fpic` would work correctly afterwards. Moreover, this approach would be portable! Here's the output of our code compiled with `-fpic` for `x86_64`: ```c-objdump Disassembly of section .text: ffff000000000070 get_address_of_global: ffff000000000070: 55 push rbp ffff000000000071: 48 89 e5 mov rbp, rsp ffff000000000074: 48 8b 05 2d 00 00 00 mov rax, qword ptr [rip + 0x2d] ffff00000000007b: 5d pop rbp ffff00000000007c: c3 ret ffff00000000007d: 0f 1f 00 nop dword ptr [rax] Disassembly of section .got: ffff0000000000a8 .got: ffff0000000000a8: 08 00 01 00 ffff0000000000ac: 00 00 ff ff Disassembly of section .data: ffff000000010008 global_data_word: ffff000000010008: 44 33 22 11 ffff00000001000c: 00 00 00 00 ``` As you can see, the `x86_64` code indirects through the `GOT` now same as the `AArch64` code. Of course, indirecting through the `GOT` would be detrimental to performance, so you would restrict `-fpic` compilation only to the code that is needed to enable the `MMU`. Everything else can be compiled `non-relocatable` as always, because the translation tables naturally resolve the **load address != link address** situation once they are live. With `C/C++` compilers, this can be done rather easily. The compilers support compilation of PIC-code on a per-[translation-unit] basis. Think of it as telling the compiler to compile this `.c` file as `PIC`, but this other `.c` file not. [translation-unit]: https://en.wikipedia.org/wiki/Translation_unit_(programming) With `Rust`, unfortunately, the [relocation model] can only be set on a per-`crate` basis at the moment (IINM), so that makes it difficult for us to put this approach to use. [relocation model]: https://doc.rust-lang.org/rustc/codegen-options/index.html#relocation-model ## Precomputed Translation Tables As we have just seen, going the `-fpic` way isn't a feasible solution at the time of writing this text. On the other hand, writing the code to set up the initial page tables in `assembly` isn't that attractive either, because writing larger pieces of assembly is an error-prone and delicate task. Fortunately, there is a third way. We are writing an embedded kernel, and therefore the execution environment is way more static and deterministic as compared to a general-purpose kernel that can be deployed on a wide variety of targets. Specifically, for the Raspberrypi, we exactly know the **load address** of the kernel in advance, and we know about the capabilities of the `MMU`. So there is nothing stopping us from precomputing the kernel's translation tables ahead of time. A disadvantage of this approach is an increased binary size, but this is not a deal breaker in our case. ## Implementation As stated in the initial `tl;dr`, we're not yet mapping the kernel to the most significant area of virtual memory. This tutorial will keep the binary `identity-mapped`, and focuses only on the infrastructure changes which enable the kernel to use `precomputed translation tables`. The actual switch to high memory will happen in the next tutorial. The changes needed are as follows: 1. Make preparations so that precomputed tables are supported by the kernel's memory subsystem code. 2. Change the boot code of the kernel so that the `MMU` is enabled with the precomputed tables as soon as possible. 3. Write a `translation table tool` that precomputes the translation tables from the generated `kernel.elf` file, and patches the tables back into the same. ### Preparing the Kernel Tables The tables must be linked into the `.data` section now so that they become part of the final binary. This is ensured using an attribute on the table's instance definition in `bsp/__board_name__/memory/mmu.rs`: ```rust #[link_section = ".data"] #[no_mangle] static KERNEL_TABLES: InitStateLock = InitStateLock::new(KernelTranslationTable::new_for_precompute()); ``` The `new_for_precompute()` is a new constructor in the the respective `_arch` code that ensures some struct members that are not the translation table entries themselves are initialized properly for the precompute use-case. The additional `#[no_mangle]` is added because we will need to parse the symbol from the `translation table tool`, and this is easier with unmangled names. In the `BSP` code, there is also a new file called `kernel_virt_addr_space_size.ld`, which contains the kernel's virtual address space size. This file gets included in both, the `kernel.ld` linker script and `mmu.rs`. We need this value both as a symbol in the kernel's ELF (for the `translation table tool` to parse it later) and as a constant in the `Rust` code. This inclusion approach is just a convenience hack that turned out working well. One critical parameter that the kernel's boot code needs in order to enable the precomputed tables is the `translation table base address` which must be programmed into the MMU's `TTBR` register. To make it accessible easily, it is added to the `.text._start_arguments` section. The definition is just below the definition of the kernel table instance in the `BSP` code: ```rust /// This value is needed during early boot for MMU setup. /// /// This will be patched to the correct value by the "translation table tool" after linking. This /// given value here is just a dummy. #[link_section = ".text._start_arguments"] #[no_mangle] static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; ``` ### Turning on the MMU Before Switching to EL1 Since the Raspberry Pi starts execution in the `EL2` privilege level, one of the first things we do during boot since `tutorial 09` is to context-switch to the appropriate `EL1`. The `EL2` boot code is a great place to set up virtual memory for `EL1`. It will allow execution in `EL1` to start with virtual memory enabled since the very first instruction. The tweaks to `boot.s` are minimal: ```asm // Load the base address of the kernel's translation tables. ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x1, __boot_core_stack_end_exclusive mov sp, x1 // Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). b _start_rust ``` In addition to the stack's address, we are now reading _the value_ of `PHYS_KERNEL_TABLES_BASE_ADDR`. The `ldr` instruction addresses the value-to-be-read using a PC-relative offset, so this is a `position-independent` operation and will therefore be future proof. The retrieved value is supplied as an argument to function `_start_rust()`, which is defined in `_arch/__arch_name__/cpu/boot.rs`: ```rust #[no_mangle] pub unsafe extern "C" fn _start_rust( phys_kernel_tables_base_addr: u64, phys_boot_core_stack_end_exclusive_addr: u64, ) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Turn on the MMU for EL1. let addr = Address::new(phys_kernel_tables_base_addr as usize); memory::mmu::enable_mmu_and_caching(addr).unwrap(); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ``` You can also see that we now turn on the `MMU` just before returning to `EL1`. That's basically it already, the only missing piece that's left is the offline computation of the translation tables. ### The Translation Table Tool The tool for translation table computation is located in the folder `$ROOT/tools/translation_table_tool`. For ease of use, it is written in `Ruby` 💎. The code is organized into `BSP` and `arch` parts just like the kernel's `Rust` code, and also has a class for processing the kernel `ELF` file: ```console $ tree tools/translation_table_tool tools/translation_table_tool ├── arch.rb ├── bsp.rb ├── generic.rb ├── kernel_elf.rb └── main.rb 0 directories, 5 files ``` Especially the `arch` part, which deals with compiling the translation table entries, will contain some overlap with the `Rust` code present in `_arch/aarch64/memory/mmu/translation_table.rs`. It might have been possible to write this tool in Rust as well, and borrow/share these pieces of code with the kernel. But in the end, I found it not worth the effort for the few lines of code. In the `Makefile`, the tool is invoked after compiling and linking the kernel, and before the `stripped binary` is generated. It's command line arguments are the target `BSP` type and the path to the kernel's `ELF` file: ```Makefile TT_TOOL_PATH = tools/translation_table_tool KERNEL_ELF_RAW = target/$(TARGET)/release/kernel # [...] KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables # [...] EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb # [...] ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Precompute the kernel translation tables and patch them into the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(TARGET) $(BSP) $(KERNEL_ELF_TTABLES) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF_TTABLES) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) ``` In `main.rb`, the `KERNEL_ELF` instance for handling the `ELF` file is created first, followed by `BSP` and `arch` parts: ```ruby KERNEL_ELF = KernelELF.new(kernel_elf_path) BSP = case BSP_TYPE when :rpi3, :rpi4 RaspberryPi.new else raise end TRANSLATION_TABLES = case KERNEL_ELF.machine when :AArch64 Arch::ARMv8::TranslationTable.new else raise end kernel_map_binary ``` Finally, the function `kernel_map_binary` is called, which kicks of a sequence of interactions between the `KERNEL_ELF`, `BSP` and `TRANSLATION_TABLES` instances: ```ruby def kernel_map_binary mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors # omitted mapping_descriptors.each do |i| print 'Generating'.rjust(12).green.bold print ' ' puts i TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) end # omitted end ``` The `generate_mapping_descriptors` method internally uses the [rbelftools](https://github.com/david942j/rbelftools) gem to parse the kernel's `ELF`. It extracts information about the various segments that comprise the kernel, as well as segment characteristics like their `virtual` and `physical` addresses (aka the mapping; still identity-mapped in this case) and the memory attributes. Part of this information can be cross-checked using the `make readelf` target if you're curious: ```console $ make readelf Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flags Align LOAD 0x0000000000010000 0x0000000000000000 0x0000000000000000 0x0000000000000000 0x0000000000080000 RW 0x10000 LOAD 0x0000000000010000 0x0000000000080000 0x0000000000080000 0x000000000000cae8 0x000000000000cae8 R E 0x10000 LOAD 0x0000000000020000 0x0000000000090000 0x0000000000090000 0x0000000000030dc0 0x0000000000030de0 RW 0x10000 Section to Segment mapping: Segment Sections... 00 .boot_core_stack 01 .text .rodata 02 .data .bss ``` The output of `generate_mapping_descriptors` is then fed into the `map_at()` method of the `TRANSLATION_TABLE` instance. For it to work properly, `TRANSLATION_TABLE` needs knowledge about **location** and **layout** of the kernel's table structure. Location will be queried from the `BSP` code, which itself retrieves it by querying `KERNEL_ELF` for the `BSP`-specific `KERNEL_TABLES` symbol. The layout, on the other hand, is hardcoded and as such must be kept in sync with the structure definition in `translation_tables.rs`. Finally, after the mappings have been created, it is time to _patch_ them back into the kernel ELF file. This is initiated from `main.rb` again: ```ruby kernel_patch_tables(kernel_elf_path) kernel_patch_base_addr(kernel_elf_path) ``` The tool prints some information on the fly. Here's the console output of a successful run: ```console $ make Compiling kernel - rpi3 Finished release [optimized] target(s) in 0.00s Precomputing kernel translation tables and patching kernel ELF ------------------------------------------------------------------------------------ Sections Virt Start Addr Phys Start Addr Size Attr ------------------------------------------------------------------------------------ Generating .boot_core_stack | 0x0000_0000_0000_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN Generating .text .rodata | 0x0000_0000_0008_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X Generating .data .bss | 0x0000_0000_0009_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN ------------------------------------------------------------------------------------ Patching Kernel table struct at ELF file offset 0x2_0000 Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0068 Finished in 0.16s ``` Please note how **only** the kernel binary is precomputed! Thanks to the changes made in the last tutorial, anything else, like `MMIO-remapping`, can and will happen lazily during runtime. ### Other changes Two more things that changed in this tutorial, but won't be explained in detail: - Since virtual memory in `EL1` is now active from the start, any attempt to convert from a kernel `Address` to `Address` is now done using the function `mmu::try_kernel_virt_addr_to_phys_addr()`, which internally uses a new function that has been added to the `TranslationTable` interface. If there is no valid virtual-to-physical mapping present in the tables, an `Err()` is returned. - The precomputed translation table mappings won't automatically have entries in the kernel's `mapping info record`, which is used to print mapping info during boot. Mapping record entries are not computed offline in order to reduce complexity. For this reason, the `BSP` code, which in earlier tutorials would have called `kernel_map_at()` (which implicitly would have generated mapping record entries), now only calls `kernel_add_mapping_record()`, since the mappings are already in place. ## Discussion It is understood that there is room for optimizations in the presented approach. For example, the generated kernel binary contains the _complete_ array of translation tables for the whole kernel virtual address space. However, most of the entries are empty initially, because the kernel binary only occupies a small area in the tables. It would make sense to add some smarts so that only the non-zero entries are packed into binary. On the other hand, this would add complexity to the code. The increased size doesn't hurt too much yet, so the reduced complexity in the code is a tradeoff made willingly to keep everything concise and focused on the high-level concepts. ## Test it ```console $ make chainboot [...] Precomputing kernel translation tables and patching kernel ELF ------------------------------------------------------------------------------------ Sections Virt Start Addr Phys Start Addr Size Attr ------------------------------------------------------------------------------------ Generating .boot_core_stack | 0x0000_0000_0000_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN Generating .text .rodata | 0x0000_0000_0008_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X Generating .data .bss | 0x0000_0000_0009_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN ------------------------------------------------------------------------------------ Patching Kernel table struct at ELF file offset 0x2_0000 Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0068 Finished in 0.15s Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 [ML] Loaded! Executing the payload now [ 2.866917] mingo version 0.15.0 [ 2.867125] Booting on: Raspberry Pi 3 [ 2.867580] MMU online: [ 2.867872] ------------------------------------------------------------------------------------------------------------------------------------------- [ 2.869616] Virtual Physical Size Attr Entity [ 2.871360] ------------------------------------------------------------------------------------------------------------------------------------------- [ 2.873105] 0x0000_0000_0000_0000..0x0000_0000_0007_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack [ 2.874709] 0x0000_0000_0008_0000..0x0000_0000_0008_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data [ 2.876322] 0x0000_0000_0009_0000..0x0000_0000_000c_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss [ 2.877893] 0x0000_0000_000d_0000..0x0000_0000_000d_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART [ 2.879410] | BCM GPIO [ 2.880861] 0x0000_0000_000e_0000..0x0000_0000_000e_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Interrupt Controller [ 2.882487] ------------------------------------------------------------------------------------------------------------------------------------------- ``` ## Diff to previous ```diff diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml --- 14_virtual_mem_part2_mmio_remap/kernel/Cargo.toml +++ 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.14.0" +version = "0.15.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs @@ -11,6 +11,7 @@ //! //! crate::cpu::boot::arch_boot +use crate::{memory, memory::Address}; use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; @@ -75,9 +76,16 @@ /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] -pub unsafe extern "C" fn _start_rust(phys_boot_core_stack_end_exclusive_addr: u64) -> ! { +pub unsafe extern "C" fn _start_rust( + phys_kernel_tables_base_addr: u64, + phys_boot_core_stack_end_exclusive_addr: u64, +) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + // Turn on the MMU for EL1. + let addr = Address::new(phys_kernel_tables_base_addr as usize); + memory::mmu::enable_mmu_and_caching(addr).unwrap(); + // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s --- 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/cpu/boot.s +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s @@ -53,19 +53,22 @@ // Prepare the jump to Rust code. .L_prepare_rust: + // Load the base address of the kernel's translation tables. + ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs + // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. - ADR_REL x0, __boot_core_stack_end_exclusive - mov sp, x0 + ADR_REL x1, __boot_core_stack_end_exclusive + mov sp, x1 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. - ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs - mrs x2, CNTFRQ_EL0 - cmp x2, xzr + ADR_REL x2, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x3, CNTFRQ_EL0 + cmp x3, xzr b.eq .L_parking_loop - str w2, [x1] + str w3, [x2] - // Jump to Rust code. x0 holds the function argument provided to _start_rust(). + // Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -125,7 +125,7 @@ } trait StartAddr { - fn phys_start_addr(&self) -> Address; + fn virt_start_addr(&self) -> Address; } //-------------------------------------------------------------------------------------------------- @@ -151,9 +151,8 @@ // Private Code //-------------------------------------------------------------------------------------------------- -// The binary is still identity mapped, so we don't need to convert here. impl StartAddr for [T; N] { - fn phys_start_addr(&self) -> Address { + fn virt_start_addr(&self) -> Address { Address::new(self as *const _ as usize) } } @@ -218,6 +217,35 @@ } } +/// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. +impl convert::TryFrom> for AttributeFields { + type Error = &'static str; + + fn try_from( + desc: InMemoryRegister, + ) -> Result { + let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { + memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, + memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, + _ => return Err("Unexpected memory attribute"), + }; + + let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, + Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, + _ => return Err("Unexpected access permission"), + }; + + let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; + + Ok(AttributeFields { + mem_attributes, + acc_perms, + execute_never, + }) + } +} + impl PageDescriptor { /// Create an instance. /// @@ -250,6 +278,19 @@ InMemoryRegister::::new(self.value) .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) } + + /// Returns the output page. + fn output_page_addr(&self) -> PageAddress { + let shifted = InMemoryRegister::::new(self.value) + .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; + + PageAddress::from(shifted << Granule64KiB::SHIFT) + } + + /// Returns the attributes. + fn try_attributes(&self) -> Result { + InMemoryRegister::::new(self.value).try_into() + } } //-------------------------------------------------------------------------------------------------- @@ -267,7 +308,7 @@ impl FixedSizeTranslationTable { /// Create an instance. #[allow(clippy::assertions_on_constants)] - pub const fn new() -> Self { + const fn _new(for_precompute: bool) -> Self { assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); // Can't have a zero-sized address space. @@ -276,10 +317,19 @@ Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], - initialized: false, + initialized: for_precompute, } } + pub const fn new_for_precompute() -> Self { + Self::_new(true) + } + + #[cfg(test)] + pub fn new_for_runtime() -> Self { + Self::_new(false) + } + /// Helper to calculate the lvl2 and lvl3 indices from an address. #[inline(always)] fn lvl2_lvl3_index_from_page_addr( @@ -297,6 +347,18 @@ Ok((lvl2_index, lvl3_index)) } + /// Returns the PageDescriptor corresponding to the supplied page address. + #[inline(always)] + fn page_descriptor_from_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result<&PageDescriptor, &'static str> { + let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; + let desc = &self.lvl3[lvl2_index][lvl3_index]; + + Ok(desc) + } + /// Sets the PageDescriptor corresponding to the supplied page address. /// /// Doesn't allow overriding an already valid page. @@ -325,24 +387,23 @@ impl memory::mmu::translation_table::interface::TranslationTable for FixedSizeTranslationTable { - fn init(&mut self) { + fn init(&mut self) -> Result<(), &'static str> { if self.initialized { - return; + return Ok(()); } // Populate the l2 entries. for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { - let phys_table_addr = self.lvl3[lvl2_nr].phys_start_addr(); + let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); + let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); *lvl2_entry = new_desc; } self.initialized = true; - } - fn phys_base_address(&self) -> Address { - self.lvl2.phys_start_addr() + Ok(()) } unsafe fn map_at( @@ -372,6 +433,45 @@ Ok(()) } + + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str> { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + Ok(page_desc.output_page_addr()) + } + + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result { + let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; + + if !page_desc.is_valid() { + return Err("Page marked invalid"); + } + + page_desc.try_attributes() + } + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str> { + let virt_page = PageAddress::from(virt_addr.align_down_page()); + let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; + + Ok(phys_page.into_inner() + virt_addr.offset_into_page()) + } } //-------------------------------------------------------------------------------------------------- diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld --- 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel.ld +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld @@ -3,6 +3,8 @@ * Copyright (c) 2018-2023 Andre Richter */ +INCLUDE kernel_virt_addr_space_size.ld; + PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; @@ -89,7 +91,7 @@ . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; - ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Misc diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld --- 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld @@ -0,0 +1 @@ +__kernel_virt_addr_space_size = 1024 * 1024 * 1024 diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/bsp/raspberrypi/memory/mmu.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -7,8 +7,8 @@ use crate::{ memory::{ mmu::{ - self as generic_mmu, AccessPermissions, AddressSpace, AssociatedTranslationTable, - AttributeFields, MemAttributes, MemoryRegion, PageAddress, TranslationGranule, + self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, + MemoryRegion, PageAddress, TranslationGranule, }, Physical, Virtual, }, @@ -31,7 +31,7 @@ pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; /// The kernel's virtual address space defined by this BSP. -pub type KernelVirtAddrSpace = AddressSpace<{ 1024 * 1024 * 1024 }>; +pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; //-------------------------------------------------------------------------------------------------- // Global instances @@ -43,13 +43,35 @@ /// /// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. /// There is a unit tests that checks this porperty. +#[link_section = ".data"] +#[no_mangle] static KERNEL_TABLES: InitStateLock = - InitStateLock::new(KernelTranslationTable::new()); + InitStateLock::new(KernelTranslationTable::new_for_precompute()); + +/// This value is needed during early boot for MMU setup. +/// +/// This will be patched to the correct value by the "translation table tool" after linking. This +/// given value here is just a dummy. +#[link_section = ".text._start_arguments"] +#[no_mangle] +static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- +/// This is a hack for retrieving the value for the kernel's virtual address space size as a +/// constant from a common place, since it is needed as a compile-time/link-time constant in both, +/// the linker script and the Rust sources. +#[allow(clippy::needless_late_init)] +const fn kernel_virt_addr_space_size() -> usize { + let __kernel_virt_addr_space_size; + + include!("../kernel_virt_addr_space_size.ld"); + + __kernel_virt_addr_space_size +} + /// Helper function for calculating the number of pages the given parameter spans. const fn size_to_num_pages(size: usize) -> usize { assert!(size > 0); @@ -88,18 +110,22 @@ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } -// The binary is still identity mapped, so use this trivial conversion function for mapping below. - +// There is no reason to expect the following conversions to fail, since they were generated offline +// by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { - MemoryRegion::new( - PageAddress::from(virt_region.start_page_addr().into_inner().as_usize()), - PageAddress::from( - virt_region - .end_exclusive_page_addr() - .into_inner() - .as_usize(), - ), - ) + let phys_start_page_addr = + generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) + .unwrap(); + + let phys_end_exclusive_page_addr = phys_start_page_addr + .checked_offset(virt_region.num_pages() as isize) + .unwrap(); + + MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) +} + +fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { + generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() } //-------------------------------------------------------------------------------------------------- @@ -121,109 +147,33 @@ MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } -/// Map the kernel binary. +/// Add mapping records for the kernel binary. /// -/// # Safety -/// -/// - Any miscalculation or attribute error will likely be fatal. Needs careful manual checking. -pub unsafe fn kernel_map_binary() -> Result<(), &'static str> { - generic_mmu::kernel_map_at( +/// The actual translation table entries for the kernel binary are generated using the offline +/// `translation table tool` and patched into the kernel binary. This function just adds the mapping +/// record entries. +pub fn kernel_add_mapping_records_for_precomputed() { + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( "Kernel boot-core stack", - &virt_boot_core_stack_region(), - &kernel_virt_to_phys_region(virt_boot_core_stack_region()), - &AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - )?; + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); - generic_mmu::kernel_map_at( + let virt_code_region = virt_code_region(); + generic_mmu::kernel_add_mapping_record( "Kernel code and RO data", - &virt_code_region(), - &kernel_virt_to_phys_region(virt_code_region()), - &AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadOnly, - execute_never: false, - }, - )?; + &virt_code_region, + &kernel_virt_to_phys_region(virt_code_region), + &kernel_page_attributes(virt_code_region.start_page_addr()), + ); - generic_mmu::kernel_map_at( + let virt_data_region = virt_data_region(); + generic_mmu::kernel_add_mapping_record( "Kernel data and bss", - &virt_data_region(), - &kernel_virt_to_phys_region(virt_data_region()), - &AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }, - )?; - - Ok(()) -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use core::{cell::UnsafeCell, ops::Range}; - use test_macros::kernel_test; - - /// Check alignment of the kernel's virtual memory layout sections. - #[kernel_test] - fn virt_mem_layout_sections_are_64KiB_aligned() { - for i in [ - virt_boot_core_stack_region, - virt_code_region, - virt_data_region, - ] - .iter() - { - let start = i().start_page_addr().into_inner(); - let end_exclusive = i().end_exclusive_page_addr().into_inner(); - - assert!(start.is_page_aligned()); - assert!(end_exclusive.is_page_aligned()); - assert!(end_exclusive >= start); - } - } - - /// Ensure the kernel's virtual memory layout is free of overlaps. - #[kernel_test] - fn virt_mem_layout_has_no_overlaps() { - let layout = [ - virt_boot_core_stack_region(), - virt_code_region(), - virt_data_region(), - ]; - - for (i, first_range) in layout.iter().enumerate() { - for second_range in layout.iter().skip(i + 1) { - assert!(!first_range.overlaps(second_range)) - } - } - } - - /// Check if KERNEL_TABLES is in .bss. - #[kernel_test] - fn kernel_tables_in_bss() { - extern "Rust" { - static __bss_start: UnsafeCell; - static __bss_end_exclusive: UnsafeCell; - } - - let bss_range = unsafe { - Range { - start: __bss_start.get(), - end: __bss_end_exclusive.get(), - } - }; - let kernel_tables_addr = &KERNEL_TABLES as *const _ as usize as *mut u64; - - assert!(bss_range.contains(&kernel_tables_addr)); - } + &virt_data_region, + &kernel_virt_to_phys_region(virt_data_region), + &kernel_page_attributes(virt_data_region.start_page_addr()), + ); } diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/lib.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs @@ -187,17 +187,7 @@ #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { - Err(string) => panic!("Error mapping kernel binary: {}", string), - Ok(addr) => addr, - }; - - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - panic!("Enabling MMU failed: {}", e); - } - - memory::mmu::post_enable_init(); + memory::init(); bsp::driver::qemu_bring_up_console(); test_main(); diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/main.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs @@ -17,27 +17,16 @@ /// Early init code. /// +/// When this code runs, virtual memory is already enabled. +/// /// # Safety /// /// - Only a single core must be active and running this function. -/// - The init calls in this function must appear in the correct order: -/// - MMU + Data caching must be activated at the earliest. Without it, any atomic operations, -/// e.g. the yet-to-be-introduced spinlocks in the device drivers (which currently employ -/// IRQSafeNullLocks instead of spinlocks), will fail to work (properly) on the RPi SoCs. +/// - Printing will not work until the respective driver's MMIO is remapped. #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { - Err(string) => panic!("Error mapping kernel binary: {}", string), - Ok(addr) => addr, - }; - - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - panic!("Enabling MMU failed: {}", e); - } - - memory::mmu::post_enable_init(); + memory::init(); // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { @@ -47,6 +36,8 @@ // Initialize all device drivers. driver::driver_manager().init_drivers_and_irqs(); + bsp::memory::mmu::kernel_add_mapping_records_for_precomputed(); + // Unmask interrupts on the boot CPU core. exception::asynchronous::local_irq_unmask(); diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu/translation_table.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs @@ -23,6 +23,8 @@ /// Translation table interfaces. pub mod interface { + use crate::memory::mmu::PageAddress; + use super::*; /// Translation table operations. @@ -33,10 +35,7 @@ /// /// - Implementor must ensure that this function can run only once or is harmless if invoked /// multiple times. - fn init(&mut self); - - /// The translation table's base address to be used for programming the MMU. - fn phys_base_address(&self) -> Address; + fn init(&mut self) -> Result<(), &'static str>; /// Map the given virtual memory region to the given physical memory region. /// @@ -53,6 +52,30 @@ phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str>; + + /// Try to translate a virtual page address to a physical page address. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_virt_page_addr_to_phys_page_addr( + &self, + virt_page_addr: PageAddress, + ) -> Result, &'static str>; + + /// Try to get the attributes of a page. + /// + /// Will only succeed if there exists a valid mapping for the input page. + fn try_page_attributes( + &self, + virt_page_addr: PageAddress, + ) -> Result; + + /// Try to translate a virtual address to a physical address. + /// + /// Will only succeed if there exists a valid mapping for the input address. + fn try_virt_addr_to_phys_addr( + &self, + virt_addr: Address, + ) -> Result, &'static str>; } } @@ -72,9 +95,9 @@ #[kernel_test] fn translationtable_implementation_sanity() { // This will occupy a lot of space on the stack. - let mut tables = MinSizeTranslationTable::new(); + let mut tables = MinSizeTranslationTable::new_for_runtime(); - tables.init(); + assert_eq!(tables.init(), Ok(())); let virt_start_page_addr: PageAddress = PageAddress::from(0); let virt_end_exclusive_page_addr: PageAddress = @@ -94,5 +117,21 @@ }; unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; + + assert_eq!( + tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), + Ok(phys_start_page_addr) + ); + + assert_eq!( + tables.try_page_attributes(virt_start_page_addr.checked_offset(6).unwrap()), + Err("Page marked invalid") + ); + + assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); + + let virt_addr = virt_start_page_addr.into_inner() + 0x100; + let phys_addr = phys_start_page_addr.into_inner() + 0x100; + assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); } } diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/memory/mmu.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs @@ -16,7 +16,8 @@ use crate::{ bsp, memory::{Address, Physical, Virtual}, - synchronization, warn, + synchronization::{self, interface::Mutex}, + warn, }; use core::{fmt, num::NonZeroUsize}; @@ -73,17 +74,9 @@ // Private Code //-------------------------------------------------------------------------------------------------- use interface::MMU; -use synchronization::interface::*; +use synchronization::interface::ReadWriteEx; use translation_table::interface::TranslationTable; -/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's -/// MMIO VA allocator with it. -fn kernel_init_mmio_va_allocator() { - let region = bsp::memory::mmu::virt_mmio_remap_region(); - - page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); -} - /// Map a region in the kernel's translation tables. /// /// No input checks done, input is passed through to the architectural implementation. @@ -101,13 +94,21 @@ bsp::memory::mmu::kernel_translation_tables() .write(|tables| tables.map_at(virt_region, phys_region, attr))?; - if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { - warn!("{}", x); - } + kernel_add_mapping_record(name, virt_region, phys_region, attr); Ok(()) } +/// Try to translate a kernel virtual address to a physical address. +/// +/// Will only succeed if there exists a valid mapping for the input address. +fn try_kernel_virt_addr_to_phys_addr( + virt_addr: Address, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) +} + //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -155,27 +156,24 @@ } } -/// Raw mapping of a virtual to physical region in the kernel translation tables. -/// -/// Prevents mapping into the MMIO range of the tables. -/// -/// # Safety -/// -/// - See `kernel_map_at_unchecked()`. -/// - Does not prevent aliasing. Currently, the callers must be trusted. -pub unsafe fn kernel_map_at( +/// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's +/// MMIO VA allocator with it. +pub fn kernel_init_mmio_va_allocator() { + let region = bsp::memory::mmu::virt_mmio_remap_region(); + + page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); +} + +/// Add an entry to the mapping info record. +pub fn kernel_add_mapping_record( name: &'static str, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, -) -> Result<(), &'static str> { - if bsp::memory::mmu::virt_mmio_remap_region().overlaps(virt_region) { - return Err("Attempt to manually map into MMIO region"); +) { + if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { + warn!("{}", x); } - - kernel_map_at_unchecked(name, virt_region, phys_region, attr)?; - - Ok(()) } /// MMIO remapping in the kernel translation tables. @@ -224,21 +222,29 @@ Ok(virt_addr + offset_into_start_page) } -/// Map the kernel's binary. Returns the translation table's base address. -/// -/// # Safety +/// Try to translate a kernel virtual page address to a physical page address. /// -/// - See [`bsp::memory::mmu::kernel_map_binary()`]. -pub unsafe fn kernel_map_binary() -> Result, &'static str> { - let phys_kernel_tables_base_addr = - bsp::memory::mmu::kernel_translation_tables().write(|tables| { - tables.init(); - tables.phys_base_address() - }); +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_virt_page_addr_to_phys_page_addr( + virt_page_addr: PageAddress, +) -> Result, &'static str> { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) +} - bsp::memory::mmu::kernel_map_binary()?; +/// Try to get the attributes of a kernel page. +/// +/// Will only succeed if there exists a valid mapping for the input page. +pub fn try_kernel_page_attributes( + virt_page_addr: PageAddress, +) -> Result { + bsp::memory::mmu::kernel_translation_tables() + .read(|tables| tables.try_page_attributes(virt_page_addr)) +} - Ok(phys_kernel_tables_base_addr) +/// Human-readable print of all recorded kernel mappings. +pub fn kernel_print_mappings() { + mapping_record::kernel_print() } /// Enable the MMU and data + instruction caching. @@ -246,56 +252,9 @@ /// # Safety /// /// - Crucial function during kernel init. Changes the the complete memory view of the processor. +#[inline(always)] pub unsafe fn enable_mmu_and_caching( phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError> { arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) } - -/// Finish initialization of the MMU subsystem. -pub fn post_enable_init() { - kernel_init_mmio_va_allocator(); -} - -/// Human-readable print of all recorded kernel mappings. -pub fn kernel_print_mappings() { - mapping_record::kernel_print() -} - -//-------------------------------------------------------------------------------------------------- -// Testing -//-------------------------------------------------------------------------------------------------- - -#[cfg(test)] -mod tests { - use super::*; - use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; - use test_macros::kernel_test; - - /// Check that you cannot map into the MMIO VA range from kernel_map_at(). - #[kernel_test] - fn no_manual_mmio_map() { - let phys_start_page_addr: PageAddress = PageAddress::from(0); - let phys_end_exclusive_page_addr: PageAddress = - phys_start_page_addr.checked_offset(5).unwrap(); - let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); - - let num_pages = NonZeroUsize::new(phys_region.num_pages()).unwrap(); - let virt_region = page_alloc::kernel_mmio_va_allocator() - .lock(|allocator| allocator.alloc(num_pages)) - .unwrap(); - - let attr = AttributeFields { - mem_attributes: MemAttributes::CacheableDRAM, - acc_perms: AccessPermissions::ReadWrite, - execute_never: true, - }; - - unsafe { - assert_eq!( - kernel_map_at("test", &virt_region, &phys_region, &attr), - Err("Attempt to manually map into MMIO region") - ) - }; - } -} diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs 15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs --- 14_virtual_mem_part2_mmio_remap/kernel/src/memory.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs @@ -136,6 +136,11 @@ } } +/// Initialize the memory subsystem. +pub fn init() { + mmu::kernel_init_mmio_va_allocator(); +} + //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs --- 14_virtual_mem_part2_mmio_remap/kernel/tests/00_console_sanity.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs @@ -18,17 +18,7 @@ use console::console; exception::handling_init(); - - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { - Err(string) => panic!("Error mapping kernel binary: {}", string), - Ok(addr) => addr, - }; - - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - panic!("Enabling MMU failed: {}", e); - } - - memory::mmu::post_enable_init(); + memory::init(); bsp::driver::qemu_bring_up_console(); // Handshake diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs --- 14_virtual_mem_part2_mmio_remap/kernel/tests/01_timer_sanity.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs @@ -17,17 +17,7 @@ #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); - - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { - Err(string) => panic!("Error mapping kernel binary: {}", string), - Ok(addr) => addr, - }; - - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - panic!("Enabling MMU failed: {}", e); - } - - memory::mmu::post_enable_init(); + memory::init(); bsp::driver::qemu_bring_up_console(); // Depending on CPU arch, some timer bring-up code could go here. Not needed for the RPi. diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs --- 14_virtual_mem_part2_mmio_remap/kernel/tests/02_exception_sync_page_fault.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs @@ -22,26 +22,12 @@ #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { - Err(string) => { - info!("Error mapping kernel binary: {}", string); - cpu::qemu_exit_failure() - } - Ok(addr) => addr, - }; - - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - info!("Enabling MMU failed: {}", e); - cpu::qemu_exit_failure() - } - - memory::mmu::post_enable_init(); - bsp::driver::qemu_bring_up_console(); - info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs --- 14_virtual_mem_part2_mmio_remap/kernel/tests/03_exception_restore_sanity.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs @@ -31,26 +31,12 @@ #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); + memory::init(); + bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing exception restore"); - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { - Err(string) => { - info!("Error mapping kernel binary: {}", string); - cpu::qemu_exit_failure() - } - Ok(addr) => addr, - }; - - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - info!("Enabling MMU failed: {}", e); - cpu::qemu_exit_failure() - } - - memory::mmu::post_enable_init(); - bsp::driver::qemu_bring_up_console(); - info!("Making a dummy system call"); // Calling this inside a function indirectly tests if the link register is restored properly. diff -uNr 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs 15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs --- 14_virtual_mem_part2_mmio_remap/kernel/tests/04_exception_irq_sanity.rs +++ 15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs @@ -15,20 +15,10 @@ #[no_mangle] unsafe fn kernel_init() -> ! { - exception::handling_init(); - - let phys_kernel_tables_base_addr = match memory::mmu::kernel_map_binary() { - Err(string) => panic!("Error mapping kernel binary: {}", string), - Ok(addr) => addr, - }; - - if let Err(e) = memory::mmu::enable_mmu_and_caching(phys_kernel_tables_base_addr) { - panic!("Enabling MMU failed: {}", e); - } - - memory::mmu::post_enable_init(); + memory::init(); bsp::driver::qemu_bring_up_console(); + exception::handling_init(); exception::asynchronous::local_irq_unmask(); test_main(); diff -uNr 14_virtual_mem_part2_mmio_remap/Makefile 15_virtual_mem_part3_precomputed_tables/Makefile --- 14_virtual_mem_part2_mmio_remap/Makefile +++ 15_virtual_mem_part3_precomputed_tables/Makefile @@ -72,10 +72,20 @@ KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config -KERNEL_ELF = target/$(TARGET)/release/kernel +KERNEL_ELF_RAW = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files -KERNEL_ELF_DEPS = $(filter-out modulo: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) +KERNEL_ELF_RAW_DEPS = $(filter-out modulo: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) + +##------------------------------------------------------------------------------ +## Translation tables +##------------------------------------------------------------------------------ +TT_TOOL_PATH = tools/translation_table_tool + +KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables +KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) + +KERNEL_ELF = $(KERNEL_ELF_TTABLES) @@ -104,6 +114,7 @@ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) +EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb @@ -154,16 +165,24 @@ ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ -$(KERNEL_ELF): $(KERNEL_ELF_DEPS) +$(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ +## Precompute the kernel translation tables and patch them into the kernel ELF +##------------------------------------------------------------------------------ +$(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) + $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") + @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) + @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) + +##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ -$(KERNEL_BIN): $(KERNEL_ELF) +$(KERNEL_BIN): $(KERNEL_ELF_TTABLES) $(call color_header, "Generating stripped binary") - @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) + @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") @@ -301,6 +320,7 @@ TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') + $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY endef diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/arch.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb --- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/arch.rb +++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb @@ -0,0 +1,312 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Bitfield manipulation. +class BitField + def initialize + @value = 0 + end + + def self.attr_bitfield(name, offset, num_bits) + define_method("#{name}=") do |bits| + mask = (2**num_bits) - 1 + + raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? + + # Clear bitfield + @value &= ~(mask << offset) + + # Set it + @value |= (bits << offset) + end + end + + def to_i + @value + end + + def size_in_byte + 8 + end +end + +# An array class that knows its memory location. +class CArray < Array + attr_reader :phys_start_addr + + def initialize(phys_start_addr, size, &block) + @phys_start_addr = phys_start_addr + + super(size, &block) + end + + def size_in_byte + inject(0) { |sum, n| sum + n.size_in_byte } + end +end + +#--------------------------------------------------------------------------------------------------- +# Arch:: +#--------------------------------------------------------------------------------------------------- +module Arch +#--------------------------------------------------------------------------------------------------- +# Arch::ARMv8 +#--------------------------------------------------------------------------------------------------- +module ARMv8 +# ARMv8 Table Descriptor. +class Stage1TableDescriptor < BitField + module NextLevelTableAddr + OFFSET = 16 + NUMBITS = 32 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + BLOCK = 0 + TABLE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def next_level_table_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__next_level_table_addr = addr + end + + private :__next_level_table_addr= +end + +# ARMv8 level 3 page descriptor. +class Stage1PageDescriptor < BitField + module UXN + OFFSET = 54 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module PXN + OFFSET = 53 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module OutputAddr + OFFSET = 16 + NUMBITS = 32 + end + + module AF + OFFSET = 10 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + module SH + OFFSET = 8 + NUMBITS = 2 + + INNER_SHAREABLE = 0b11 + end + + module AP + OFFSET = 6 + NUMBITS = 2 + + RW_EL1 = 0b00 + RO_EL1 = 0b10 + end + + module AttrIndx + OFFSET = 2 + NUMBITS = 3 + end + + module Type + OFFSET = 1 + NUMBITS = 1 + + RESERVED_INVALID = 0 + PAGE = 1 + end + + module Valid + OFFSET = 0 + NUMBITS = 1 + + FALSE = 0 + TRUE = 1 + end + + attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) + attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) + attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) + attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) + attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) + attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) + attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) + attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) + attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) + + def output_addr=(addr) + addr >>= Granule64KiB::SHIFT + + self.__output_addr = addr + end + + private :__output_addr= +end + +# Translation table representing the structure defined in translation_table.rs. +class TranslationTable + module MAIR + NORMAL = 1 + end + + def initialize + do_sanity_checks + + num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT + + @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) + + @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte + @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) + + populate_lvl2_entries + end + + def map_at(virt_region, phys_region, attributes) + return if virt_region.empty? + + raise if virt_region.size != phys_region.size + raise if phys_region.last > BSP.phys_addr_space_end_page + + virt_region.zip(phys_region).each do |virt_page, phys_page| + desc = page_descriptor_from(virt_page) + set_lvl3_entry(desc, phys_page, attributes) + end + end + + def to_binary + data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) + data.pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr_binary + [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian + end + + def phys_tables_base_addr + @lvl2_phys_start_addr + end + + private + + def do_sanity_checks + raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE + raise unless (BSP.kernel_virt_addr_space_size modulo Granule512MiB::SIZE).zero? + end + + def new_lvl3(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + temp = CArray.new(start_addr, 8192) do + Stage1PageDescriptor.new + end + start_addr += temp.size_in_byte + + temp + end + end + + def new_lvl2(num_lvl2_tables, start_addr) + CArray.new(start_addr, num_lvl2_tables) do + Stage1TableDescriptor.new + end + end + + def populate_lvl2_entries + @lvl2.each_with_index do |descriptor, i| + descriptor.next_level_table_addr = @lvl3[i].phys_start_addr + descriptor.type = Stage1TableDescriptor::Type::TABLE + descriptor.valid = Stage1TableDescriptor::Valid::TRUE + end + end + + def lvl2_lvl3_index_from(addr) + lvl2_index = addr >> Granule512MiB::SHIFT + lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT + + raise unless lvl2_index < @lvl2.size + + [lvl2_index, lvl3_index] + end + + def page_descriptor_from(virt_addr) + lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) + + @lvl3[lvl2_index][lvl3_index] + end + + # rubocop:disable Metrics/MethodLength + def set_attributes(desc, attributes) + case attributes.mem_attributes + when :CacheableDRAM + desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE + desc.attr_indx = MAIR::NORMAL + else + raise 'Invalid input' + end + + desc.ap = case attributes.acc_perms + when :ReadOnly + Stage1PageDescriptor::AP::RO_EL1 + when :ReadWrite + Stage1PageDescriptor::AP::RW_EL1 + else + raise 'Invalid input' + + end + + desc.pxn = if attributes.execute_never + Stage1PageDescriptor::PXN::TRUE + else + Stage1PageDescriptor::PXN::FALSE + end + + desc.uxn = Stage1PageDescriptor::UXN::TRUE + end + # rubocop:enable Metrics/MethodLength + + def set_lvl3_entry(desc, output_addr, attributes) + desc.output_addr = output_addr + desc.af = Stage1PageDescriptor::AF::TRUE + desc.type = Stage1PageDescriptor::Type::PAGE + desc.valid = Stage1PageDescriptor::Valid::TRUE + + set_attributes(desc, attributes) + end +end +end +end diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/bsp.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb --- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/bsp.rb +++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# Raspberry Pi 3 + 4 +class RaspberryPi + attr_reader :kernel_granule, :kernel_virt_addr_space_size + + MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") + + def initialize + @kernel_granule = Granule64KiB + + @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + + @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') + @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( + 'PHYS_KERNEL_TABLES_BASE_ADDR' + ) + end + + def phys_addr_of_kernel_tables + KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) + end + + def kernel_tables_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) + end + + def phys_kernel_tables_base_addr_offset_in_file + KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) + end + + def phys_addr_space_end_page + x = MEMORY_SRC.grep(/pub const END/) + x = case BSP_TYPE + when :rpi3 + x[0] + when :rpi4 + x[1] + else + raise + end + + x.scan(/\d+/).join.to_i(16) + end +end diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/generic.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb --- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/generic.rb +++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb @@ -0,0 +1,179 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +module Granule64KiB + SIZE = 64 * 1024 + SHIFT = Math.log2(SIZE).to_i +end + +module Granule512MiB + SIZE = 512 * 1024 * 1024 + SHIFT = Math.log2(SIZE).to_i + MASK = SIZE - 1 +end + +# Monkey-patch Integer with some helper functions. +class Integer + def power_of_two? + self[0].zero? + end + + def aligned?(alignment) + raise unless alignment.power_of_two? + + (self & (alignment - 1)).zero? + end + + def align_up(alignment) + raise unless alignment.power_of_two? + + (self + alignment - 1) & ~(alignment - 1) + end + + def to_hex_underscore(with_leading_zeros: false) + fmt = with_leading_zeros ? 'modulo016x' : 'modulox' + value = format(fmt, self).to_s.reverse.scan(/.{4}|.+/).join('_').reverse + + format('0xmodulos', value) + end +end + +# An array where each value is the start address of a Page. +class MemoryRegion < Array + def initialize(start_addr, size, granule_size) + raise unless start_addr.aligned?(granule_size) + raise unless size.positive? + raise unless (size modulo granule_size).zero? + + num_pages = size / granule_size + super(num_pages) do |i| + (i * granule_size) + start_addr + end + end +end + +# Collection of memory attributes. +class AttributeFields + attr_reader :mem_attributes, :acc_perms, :execute_never + + def initialize(mem_attributes, acc_perms, execute_never) + @mem_attributes = mem_attributes + @acc_perms = acc_perms + @execute_never = execute_never + end + + def to_s + x = case @mem_attributes + when :CacheableDRAM + 'C' + else + '?' + end + + y = case @acc_perms + when :ReadWrite + 'RW' + when :ReadOnly + 'RO' + else + '??' + end + + z = @execute_never ? 'XN' : 'X ' + + "#{x} #{y} #{z}" + end +end + +# A container that describes a virt-to-phys region mapping. +class MappingDescriptor + @max_section_name_length = 'Sections'.length + + class << self + attr_accessor :max_section_name_length + + def update_max_section_name_length(length) + @max_section_name_length = [@max_section_name_length, length].max + end + end + + attr_reader :name, :virt_region, :phys_region, :attributes + + def initialize(name, virt_region, phys_region, attributes) + @name = name + @virt_region = virt_region + @phys_region = phys_region + @attributes = attributes + end + + def to_s + name = @name.ljust(self.class.max_section_name_length) + virt_start = @virt_region.first.to_hex_underscore(with_leading_zeros: true) + phys_start = @phys_region.first.to_hex_underscore(with_leading_zeros: true) + size = ((@virt_region.size * 65_536) / 1024).to_s.rjust(3) + + "#{name} | #{virt_start} | #{phys_start} | #{size} KiB | #{@attributes}" + end + + def self.print_divider + print ' ' + print '-' * max_section_name_length + puts '--------------------------------------------------------------------' + end + + def self.print_header + print_divider + print ' ' + print 'Sections'.center(max_section_name_length) + print ' ' + print 'Virt Start Addr'.center(21) + print ' ' + print 'Phys Start Addr'.center(21) + print ' ' + print 'Size'.center(7) + print ' ' + print 'Attr'.center(7) + puts + print_divider + end +end + +def kernel_map_binary + mapping_descriptors = KERNEL_ELF.generate_mapping_descriptors + + # Generate_mapping_descriptors updates the header being printed with this call. So it must come + # afterwards. + MappingDescriptor.print_header + + mapping_descriptors.each do |i| + print 'Generating'.rjust(12).green.bold + print ' ' + puts i + + TRANSLATION_TABLES.map_at(i.virt_region, i.phys_region, i.attributes) + end + + MappingDescriptor.print_divider +end + +def kernel_patch_tables(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel table struct at ELF file offset ' + puts BSP.kernel_tables_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.to_binary, BSP.kernel_tables_offset_in_file) +end + +def kernel_patch_base_addr(kernel_elf_path) + print 'Patching'.rjust(12).green.bold + print ' Kernel tables physical base address start argument to value ' + print TRANSLATION_TABLES.phys_tables_base_addr.to_hex_underscore + print ' at ELF file offset ' + puts BSP.phys_kernel_tables_base_addr_offset_in_file.to_hex_underscore + + File.binwrite(kernel_elf_path, TRANSLATION_TABLES.phys_tables_base_addr_binary, + BSP.phys_kernel_tables_base_addr_offset_in_file) +end diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/kernel_elf.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb --- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/kernel_elf.rb +++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +# KernelELF +class KernelELF + SECTION_FLAG_ALLOC = 2 + + def initialize(kernel_elf_path) + @elf = ELFTools::ELFFile.new(File.open(kernel_elf_path)) + @symtab_section = @elf.section_by_name('.symtab') + end + + def machine + @elf.machine.to_sym + end + + def symbol_value(symbol_name) + @symtab_section.symbol_by_name(symbol_name).header.st_value + end + + def segment_containing_virt_addr(virt_addr) + @elf.each_segments do |segment| + return segment if segment.vma_in?(virt_addr) + end + end + + def virt_to_phys(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + translation_offset = segment.header.p_vaddr - segment.header.p_paddr + + virt_addr - translation_offset + end + + def virt_addr_to_file_offset(virt_addr) + segment = segment_containing_virt_addr(virt_addr) + segment.vma_to_offset(virt_addr) + end + + def sections_in_segment(segment) + head = segment.mem_head + tail = segment.mem_tail + + sections = @elf.each_sections.select do |section| + file_offset = section.header.sh_addr + flags = section.header.sh_flags + + file_offset >= head && file_offset < tail && (flags & SECTION_FLAG_ALLOC != 0) + end + + sections.map(&:name).join(' ') + end + + def select_load_segments + @elf.each_segments.select do |segment| + segment.instance_of?(ELFTools::Segments::LoadSegment) + end + end + + def segment_get_acc_perms(segment) + if segment.readable? && segment.writable? + :ReadWrite + elsif segment.readable? + :ReadOnly + else + :Invalid + end + end + + def update_max_section_name_length(descriptors) + MappingDescriptor.update_max_section_name_length(descriptors.map { |i| i.name.size }.max) + end + + def generate_mapping_descriptors + descriptors = select_load_segments.map do |segment| + # Assume each segment is page aligned. + size = segment.mem_size.align_up(BSP.kernel_granule::SIZE) + virt_start_addr = segment.header.p_vaddr + phys_start_addr = segment.header.p_paddr + acc_perms = segment_get_acc_perms(segment) + execute_never = !segment.executable? + section_names = sections_in_segment(segment) + + virt_region = MemoryRegion.new(virt_start_addr, size, BSP.kernel_granule::SIZE) + phys_region = MemoryRegion.new(phys_start_addr, size, BSP.kernel_granule::SIZE) + attributes = AttributeFields.new(:CacheableDRAM, acc_perms, execute_never) + + MappingDescriptor.new(section_names, virt_region, phys_region, attributes) + end + + update_max_section_name_length(descriptors) + descriptors + end +end diff -uNr 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/main.rb 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb --- 14_virtual_mem_part2_mmio_remap/tools/translation_table_tool/main.rb +++ 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb @@ -0,0 +1,46 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# SPDX-License-Identifier: MIT OR Apache-2.0 +# +# Copyright (c) 2021-2023 Andre Richter + +require 'rubygems' +require 'bundler/setup' +require 'colorize' +require 'elftools' + +require_relative 'generic' +require_relative 'kernel_elf' +require_relative 'bsp' +require_relative 'arch' + +BSP_TYPE = ARGV[0].to_sym +kernel_elf_path = ARGV[1] + +start = Time.now + +KERNEL_ELF = KernelELF.new(kernel_elf_path) + +BSP = case BSP_TYPE + when :rpi3, :rpi4 + RaspberryPi.new + else + raise + end + +TRANSLATION_TABLES = case KERNEL_ELF.machine + when :AArch64 + Arch::ARMv8::TranslationTable.new + else + raise + end + +kernel_map_binary +kernel_patch_tables(kernel_elf_path) +kernel_patch_base_addr(kernel_elf_path) + +elapsed = Time.now - start + +print 'Finished'.rjust(12).green.bold +puts " in #{elapsed.round(2)}s" ``` ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/build.rs ================================================ 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())); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use crate::{memory, memory::Address}; use aarch64_cpu::{asm, registers::*}; use core::arch::global_asm; use tock_registers::interfaces::Writeable; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CURRENTEL_EL2 = const 0x8, CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Prepares the transition from EL2 to EL1. /// /// # Safety /// /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); // No offset for reading the counters. CNTVOFF_EL2.set(0); // Set EL1 execution state to AArch64. HCR_EL2.write(HCR_EL2::RW::EL1IsAarch64); // Set up a simulated exception return. // // First, fake a saved program status where all interrupts were masked and SP_EL1 was used as a // stack pointer. SPSR_EL2.write( SPSR_EL2::D::Masked + SPSR_EL2::A::Masked + SPSR_EL2::I::Masked + SPSR_EL2::F::Masked + SPSR_EL2::M::EL1h, ); // Second, let the link register point to kernel_init(). ELR_EL2.set(crate::kernel_init as *const () as u64); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. /// /// # Safety /// /// - Exception return from EL2 must must continue execution in EL1 with `kernel_init()`. #[no_mangle] pub unsafe extern "C" fn _start_rust( phys_kernel_tables_base_addr: u64, phys_boot_core_stack_end_exclusive_addr: u64, ) -> ! { prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); // Turn on the MMU for EL1. let addr = Address::new(phys_kernel_tables_base_addr as usize); memory::mmu::enable_mmu_and_caching(addr).unwrap(); // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. asm::eret() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2022 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed if the core executes in EL2. Park it otherwise. mrs x0, CurrentEL cmp x0, {CONST_CURRENTEL_EL2} b.ne .L_parking_loop // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Load the base address of the kernel's translation tables. ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. ADR_REL x1, __boot_core_stack_end_exclusive mov sp, x1 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x2, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x3, CNTFRQ_EL0 cmp x3, xzr b.eq .L_parking_loop str w3, [x2] // Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural translation table. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::translation_table::arch_translation_table use crate::{ bsp, memory::{ self, mmu::{ arch_mmu::{Granule512MiB, Granule64KiB}, AccessPermissions, AttributeFields, MemAttributes, MemoryRegion, PageAddress, }, Address, Physical, Virtual, }, }; use core::convert; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, registers::InMemoryRegister, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // A table descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-15. register_bitfields! {u64, STAGE1_TABLE_DESCRIPTOR [ /// Physical address of the next descriptor. NEXT_LEVEL_TABLE_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] TYPE OFFSET(1) NUMBITS(1) [ Block = 0, Table = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } // A level 3 page descriptor, as per ARMv8-A Architecture Reference Manual Figure D5-17. register_bitfields! {u64, STAGE1_PAGE_DESCRIPTOR [ /// Unprivileged execute-never. UXN OFFSET(54) NUMBITS(1) [ False = 0, True = 1 ], /// Privileged execute-never. PXN OFFSET(53) NUMBITS(1) [ False = 0, True = 1 ], /// Physical address of the next table descriptor (lvl2) or the page descriptor (lvl3). OUTPUT_ADDR_64KiB OFFSET(16) NUMBITS(32) [], // [47:16] /// Access flag. AF OFFSET(10) NUMBITS(1) [ False = 0, True = 1 ], /// Shareability field. SH OFFSET(8) NUMBITS(2) [ OuterShareable = 0b10, InnerShareable = 0b11 ], /// Access Permissions. AP OFFSET(6) NUMBITS(2) [ RW_EL1 = 0b00, RW_EL1_EL0 = 0b01, RO_EL1 = 0b10, RO_EL1_EL0 = 0b11 ], /// Memory attributes index into the MAIR_EL1 register. AttrIndx OFFSET(2) NUMBITS(3) [], TYPE OFFSET(1) NUMBITS(1) [ Reserved_Invalid = 0, Page = 1 ], VALID OFFSET(0) NUMBITS(1) [ False = 0, True = 1 ] ] } /// A table descriptor for 64 KiB aperture. /// /// The output points to the next table. #[derive(Copy, Clone)] #[repr(C)] struct TableDescriptor { value: u64, } /// A page descriptor with 64 KiB aperture. /// /// The output points to physical memory. #[derive(Copy, Clone)] #[repr(C)] struct PageDescriptor { value: u64, } trait StartAddr { fn virt_start_addr(&self) -> Address; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Big monolithic struct for storing the translation tables. Individual levels must be 64 KiB /// aligned, so the lvl3 is put first. #[repr(C)] #[repr(align(65536))] pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], /// Table descriptors, covering 512 MiB windows. lvl2: [TableDescriptor; NUM_TABLES], /// Have the tables been initialized? initialized: bool, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl StartAddr for [T; N] { fn virt_start_addr(&self) -> Address { Address::new(self as *const _ as usize) } } impl TableDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance pointing to the supplied address. pub fn from_next_lvl_table_addr(phys_next_lvl_table_addr: Address) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_next_lvl_table_addr.as_usize() >> Granule64KiB::SHIFT; val.write( STAGE1_TABLE_DESCRIPTOR::NEXT_LEVEL_TABLE_ADDR_64KiB.val(shifted as u64) + STAGE1_TABLE_DESCRIPTOR::TYPE::Table + STAGE1_TABLE_DESCRIPTOR::VALID::True, ); TableDescriptor { value: val.get() } } } /// Convert the kernel's generic memory attributes to HW-specific attributes of the MMU. impl convert::From for tock_registers::fields::FieldValue { fn from(attribute_fields: AttributeFields) -> Self { // Memory attributes. let mut desc = match attribute_fields.mem_attributes { MemAttributes::CacheableDRAM => { STAGE1_PAGE_DESCRIPTOR::SH::InnerShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::NORMAL) } MemAttributes::Device => { STAGE1_PAGE_DESCRIPTOR::SH::OuterShareable + STAGE1_PAGE_DESCRIPTOR::AttrIndx.val(memory::mmu::arch_mmu::mair::DEVICE) } }; // Access Permissions. desc += match attribute_fields.acc_perms { AccessPermissions::ReadOnly => STAGE1_PAGE_DESCRIPTOR::AP::RO_EL1, AccessPermissions::ReadWrite => STAGE1_PAGE_DESCRIPTOR::AP::RW_EL1, }; // The execute-never attribute is mapped to PXN in AArch64. desc += if attribute_fields.execute_never { STAGE1_PAGE_DESCRIPTOR::PXN::True } else { STAGE1_PAGE_DESCRIPTOR::PXN::False }; // Always set unprivileged exectue-never as long as userspace is not implemented yet. desc += STAGE1_PAGE_DESCRIPTOR::UXN::True; desc } } /// Convert the HW-specific attributes of the MMU to kernel's generic memory attributes. impl convert::TryFrom> for AttributeFields { type Error = &'static str; fn try_from( desc: InMemoryRegister, ) -> Result { let mem_attributes = match desc.read(STAGE1_PAGE_DESCRIPTOR::AttrIndx) { memory::mmu::arch_mmu::mair::NORMAL => MemAttributes::CacheableDRAM, memory::mmu::arch_mmu::mair::DEVICE => MemAttributes::Device, _ => return Err("Unexpected memory attribute"), }; let acc_perms = match desc.read_as_enum(STAGE1_PAGE_DESCRIPTOR::AP) { Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RO_EL1) => AccessPermissions::ReadOnly, Some(STAGE1_PAGE_DESCRIPTOR::AP::Value::RW_EL1) => AccessPermissions::ReadWrite, _ => return Err("Unexpected access permission"), }; let execute_never = desc.read(STAGE1_PAGE_DESCRIPTOR::PXN) > 0; Ok(AttributeFields { mem_attributes, acc_perms, execute_never, }) } } impl PageDescriptor { /// Create an instance. /// /// Descriptor is invalid by default. pub const fn new_zeroed() -> Self { Self { value: 0 } } /// Create an instance. pub fn from_output_page_addr( phys_output_page_addr: PageAddress, attribute_fields: &AttributeFields, ) -> Self { let val = InMemoryRegister::::new(0); let shifted = phys_output_page_addr.into_inner().as_usize() >> Granule64KiB::SHIFT; val.write( STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB.val(shifted as u64) + STAGE1_PAGE_DESCRIPTOR::AF::True + STAGE1_PAGE_DESCRIPTOR::TYPE::Page + STAGE1_PAGE_DESCRIPTOR::VALID::True + (*attribute_fields).into(), ); Self { value: val.get() } } /// Returns the valid bit. fn is_valid(&self) -> bool { InMemoryRegister::::new(self.value) .is_set(STAGE1_PAGE_DESCRIPTOR::VALID) } /// Returns the output page. fn output_page_addr(&self) -> PageAddress { let shifted = InMemoryRegister::::new(self.value) .read(STAGE1_PAGE_DESCRIPTOR::OUTPUT_ADDR_64KiB) as usize; PageAddress::from(shifted << Granule64KiB::SHIFT) } /// Returns the attributes. fn try_attributes(&self) -> Result { InMemoryRegister::::new(self.value).try_into() } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AssociatedTranslationTable for memory::mmu::AddressSpace where [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, { type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; } impl FixedSizeTranslationTable { /// Create an instance. #[allow(clippy::assertions_on_constants)] const fn _new(for_precompute: bool) -> Self { assert!(bsp::memory::mmu::KernelGranule::SIZE == Granule64KiB::SIZE); // Can't have a zero-sized address space. assert!(NUM_TABLES > 0); Self { lvl3: [[PageDescriptor::new_zeroed(); 8192]; NUM_TABLES], lvl2: [TableDescriptor::new_zeroed(); NUM_TABLES], initialized: for_precompute, } } pub const fn new_for_precompute() -> Self { Self::_new(true) } #[cfg(test)] pub fn new_for_runtime() -> Self { Self::_new(false) } /// Helper to calculate the lvl2 and lvl3 indices from an address. #[inline(always)] fn lvl2_lvl3_index_from_page_addr( &self, virt_page_addr: PageAddress, ) -> Result<(usize, usize), &'static str> { let addr = virt_page_addr.into_inner().as_usize(); let lvl2_index = addr >> Granule512MiB::SHIFT; let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; if lvl2_index > (NUM_TABLES - 1) { return Err("Virtual page is out of bounds of translation table"); } Ok((lvl2_index, lvl3_index)) } /// Returns the PageDescriptor corresponding to the supplied page address. #[inline(always)] fn page_descriptor_from_page_addr( &self, virt_page_addr: PageAddress, ) -> Result<&PageDescriptor, &'static str> { let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; let desc = &self.lvl3[lvl2_index][lvl3_index]; Ok(desc) } /// Sets the PageDescriptor corresponding to the supplied page address. /// /// Doesn't allow overriding an already valid page. #[inline(always)] fn set_page_descriptor_from_page_addr( &mut self, virt_page_addr: PageAddress, new_desc: &PageDescriptor, ) -> Result<(), &'static str> { let (lvl2_index, lvl3_index) = self.lvl2_lvl3_index_from_page_addr(virt_page_addr)?; let desc = &mut self.lvl3[lvl2_index][lvl3_index]; if desc.is_valid() { return Err("Virtual page is already mapped"); } *desc = *new_desc; Ok(()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl memory::mmu::translation_table::interface::TranslationTable for FixedSizeTranslationTable { fn init(&mut self) -> Result<(), &'static str> { if self.initialized { return Ok(()); } // Populate the l2 entries. for (lvl2_nr, lvl2_entry) in self.lvl2.iter_mut().enumerate() { let virt_table_addr = self.lvl3[lvl2_nr].virt_start_addr(); let phys_table_addr = memory::mmu::try_kernel_virt_addr_to_phys_addr(virt_table_addr)?; let new_desc = TableDescriptor::from_next_lvl_table_addr(phys_table_addr); *lvl2_entry = new_desc; } self.initialized = true; Ok(()) } unsafe fn map_at( &mut self, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str> { assert!(self.initialized, "Translation tables not initialized"); if virt_region.size() != phys_region.size() { return Err("Tried to map memory regions with unequal sizes"); } if phys_region.end_exclusive_page_addr() > bsp::memory::phys_addr_space_end_exclusive_addr() { return Err("Tried to map outside of physical address space"); } let iter = phys_region.into_iter().zip(virt_region.into_iter()); for (phys_page_addr, virt_page_addr) in iter { let new_desc = PageDescriptor::from_output_page_addr(phys_page_addr, attr); let virt_page = virt_page_addr; self.set_page_descriptor_from_page_addr(virt_page, &new_desc)?; } Ok(()) } fn try_virt_page_addr_to_phys_page_addr( &self, virt_page_addr: PageAddress, ) -> Result, &'static str> { let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; if !page_desc.is_valid() { return Err("Page marked invalid"); } Ok(page_desc.output_page_addr()) } fn try_page_attributes( &self, virt_page_addr: PageAddress, ) -> Result { let page_desc = self.page_descriptor_from_page_addr(virt_page_addr)?; if !page_desc.is_valid() { return Err("Page marked invalid"); } page_desc.try_attributes() } /// Try to translate a virtual address to a physical address. /// /// Will only succeed if there exists a valid mapping for the input address. fn try_virt_addr_to_phys_addr( &self, virt_addr: Address, ) -> Result, &'static str> { let virt_page = PageAddress::from(virt_addr.align_down_page()); let phys_page = self.try_virt_page_addr_to_phys_page_addr(virt_page)?; Ok(phys_page.into_inner() + virt_addr.offset_into_page()) } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; #[cfg(test)] mod tests { use super::*; use test_macros::kernel_test; /// Check if the size of `struct TableDescriptor` is as expected. #[kernel_test] fn size_of_tabledescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } /// Check if the size of `struct PageDescriptor` is as expected. #[kernel_test] fn size_of_pagedescriptor_equals_64_bit() { assert_eq!( core::mem::size_of::(), core::mem::size_of::() ); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Memory Management Unit Driver. //! //! Only 64 KiB granule is supported. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::memory::mmu::arch_mmu use crate::{ bsp, memory, memory::{mmu::TranslationGranule, Address, Physical}, }; use aarch64_cpu::{asm::barrier, registers::*}; use core::intrinsics::unlikely; use tock_registers::interfaces::{ReadWriteable, Readable, Writeable}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- /// Memory Management Unit type. struct MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub type Granule512MiB = TranslationGranule<{ 512 * 1024 * 1024 }>; pub type Granule64KiB = TranslationGranule<{ 64 * 1024 }>; /// Constants for indexing the MAIR_EL1. #[allow(dead_code)] pub mod mair { pub const DEVICE: u64 = 0; pub const NORMAL: u64 = 1; } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static MMU: MemoryManagementUnit = MemoryManagementUnit; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl memory::mmu::AddressSpace { /// Checks for architectural restrictions. pub const fn arch_address_space_size_sanity_checks() { // Size must be at least one full 512 MiB table. assert!((AS_SIZE % Granule512MiB::SIZE) == 0); // Check for 48 bit virtual address size as maximum, which is supported by any ARMv8 // version. assert!(AS_SIZE <= (1 << 48)); } } impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( // Attribute 1 - Cacheable normal DRAM. MAIR_EL1::Attr1_Normal_Outer::WriteBack_NonTransient_ReadWriteAlloc + MAIR_EL1::Attr1_Normal_Inner::WriteBack_NonTransient_ReadWriteAlloc + // Attribute 0 - Device. MAIR_EL1::Attr0_Device::nonGathering_nonReordering_EarlyWriteAck, ); } /// Configure various settings of stage 1 of the EL1 translation regime. fn configure_translation_control(&self) { let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( TCR_EL1::TBI0::Used + TCR_EL1::IPS::Bits_40 + TCR_EL1::TG0::KiB_64 + TCR_EL1::SH0::Inner + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable + TCR_EL1::EPD0::EnableTTBR0Walks + TCR_EL1::A1::TTBR0 + TCR_EL1::T0SZ.val(t0sz) + TCR_EL1::EPD1::DisableTTBR1Walks, ); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the MMU instance. pub fn mmu() -> &'static impl memory::mmu::interface::MMU { &MMU } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use memory::mmu::MMUEnableError; impl memory::mmu::interface::MMU for MemoryManagementUnit { unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError> { if unlikely(self.is_enabled()) { return Err(MMUEnableError::AlreadyEnabled); } // Fail early if translation granule is not supported. if unlikely(!ID_AA64MMFR0_EL1.matches_all(ID_AA64MMFR0_EL1::TGran64::Supported)) { return Err(MMUEnableError::Other( "Translation granule not supported in HW", )); } // Prepare the memory attribute indirection register. self.set_up_mair(); // Set the "Translation Table Base Register". TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); self.configure_translation_control(); // Switch the MMU on. // // First, force all previous changes to be seen before the MMU is enabled. barrier::isb(barrier::SY); // Enable the MMU and turn on data and instruction caching. SCTLR_EL1.modify(SCTLR_EL1::M::Enable + SCTLR_EL1::C::Cacheable + SCTLR_EL1::I::Cacheable); // Force MMU init to complete before next instruction. barrier::isb(barrier::SY); Ok(()) } #[inline(always)] fn is_enabled(&self) -> bool { SCTLR_EL1.matches_all(SCTLR_EL1::M::Enable) } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // 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)); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // 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); }); } } } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // 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()); } } }); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // 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 } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // 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()); } } }); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // 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(); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // 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(()) } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver/common.rs ================================================ // 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) } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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()); }; } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ INCLUDE kernel_virt_addr_space_size.ld; PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW * * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. * It doesn't mean all of them need actually be loaded. */ PHDRS { segment_boot_core_stack PT_LOAD FLAGS(6); segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); } SECTIONS { . = __rpi_phys_dram_start_addr; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : { __boot_core_stack_start = .; /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __code_start = .; .text : { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ *(.text._start_rust) /* The Rust entry point */ *(.text*) /* Everything else */ } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ __data_start = .; .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { __bss_start = .; *(.bss*); . = ALIGN(16); __bss_end_exclusive = .; } :segment_data . = ALIGN(PAGE_SIZE); __data_end_exclusive = .; /*********************************************************************************************** * MMIO Remap Reserved ***********************************************************************************************/ __mmio_remap_start = .; . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Misc ***********************************************************************************************/ .got : { *(.got*) } ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") /DISCARD/ : { *(.comment*) } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ================================================ __kernel_virt_addr_space_size = 1024 * 1024 * 1024 ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management Unit. use crate::{ memory::{ mmu::{ self as generic_mmu, AddressSpace, AssociatedTranslationTable, AttributeFields, MemoryRegion, PageAddress, TranslationGranule, }, Physical, Virtual, }, synchronization::InitStateLock, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- type KernelTranslationTable = ::TableStartFromBottom; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The translation granule chosen by this BSP. This will be used everywhere else in the kernel to /// derive respective data structures and their sizes. For example, the `crate::memory::mmu::Page`. pub type KernelGranule = TranslationGranule<{ 64 * 1024 }>; /// The kernel's virtual address space defined by this BSP. pub type KernelVirtAddrSpace = AddressSpace<{ kernel_virt_addr_space_size() }>; //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- /// The kernel translation tables. /// /// It is mandatory that InitStateLock is transparent. /// /// That is, `size_of(InitStateLock) == size_of(KernelTranslationTable)`. /// There is a unit tests that checks this porperty. #[link_section = ".data"] #[no_mangle] static KERNEL_TABLES: InitStateLock = InitStateLock::new(KernelTranslationTable::new_for_precompute()); /// This value is needed during early boot for MMU setup. /// /// This will be patched to the correct value by the "translation table tool" after linking. This /// given value here is just a dummy. #[link_section = ".text._start_arguments"] #[no_mangle] static PHYS_KERNEL_TABLES_BASE_ADDR: u64 = 0xCCCCAAAAFFFFEEEE; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// This is a hack for retrieving the value for the kernel's virtual address space size as a /// constant from a common place, since it is needed as a compile-time/link-time constant in both, /// the linker script and the Rust sources. #[allow(clippy::needless_late_init)] const fn kernel_virt_addr_space_size() -> usize { let __kernel_virt_addr_space_size; include!("../kernel_virt_addr_space_size.ld"); __kernel_virt_addr_space_size } /// Helper function for calculating the number of pages the given parameter spans. const fn size_to_num_pages(size: usize) -> usize { assert!(size > 0); assert!(size % KernelGranule::SIZE == 0); size >> KernelGranule::SHIFT } /// The code pages of the kernel binary. fn virt_code_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::code_size()); let start_page_addr = super::virt_code_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } /// The data pages of the kernel binary. fn virt_data_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::data_size()); let start_page_addr = super::virt_data_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } /// The boot core stack pages. fn virt_boot_core_stack_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::boot_core_stack_size()); let start_page_addr = super::virt_boot_core_stack_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } // There is no reason to expect the following conversions to fail, since they were generated offline // by the `translation table tool`. If it doesn't work, a panic due to the unwraps is justified. fn kernel_virt_to_phys_region(virt_region: MemoryRegion) -> MemoryRegion { let phys_start_page_addr = generic_mmu::try_kernel_virt_page_addr_to_phys_page_addr(virt_region.start_page_addr()) .unwrap(); let phys_end_exclusive_page_addr = phys_start_page_addr .checked_offset(virt_region.num_pages() as isize) .unwrap(); MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr) } fn kernel_page_attributes(virt_page_addr: PageAddress) -> AttributeFields { generic_mmu::try_kernel_page_attributes(virt_page_addr).unwrap() } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Return a reference to the kernel's translation tables. pub fn kernel_translation_tables() -> &'static InitStateLock { &KERNEL_TABLES } /// The MMIO remap pages. pub fn virt_mmio_remap_region() -> MemoryRegion { let num_pages = size_to_num_pages(super::mmio_remap_size()); let start_page_addr = super::virt_mmio_remap_start(); let end_exclusive_page_addr = start_page_addr.checked_offset(num_pages as isize).unwrap(); MemoryRegion::new(start_page_addr, end_exclusive_page_addr) } /// Add mapping records for the kernel binary. /// /// The actual translation table entries for the kernel binary are generated using the offline /// `translation table tool` and patched into the kernel binary. This function just adds the mapping /// record entries. pub fn kernel_add_mapping_records_for_precomputed() { let virt_boot_core_stack_region = virt_boot_core_stack_region(); generic_mmu::kernel_add_mapping_record( "Kernel boot-core stack", &virt_boot_core_stack_region, &kernel_virt_to_phys_region(virt_boot_core_stack_region), &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), ); let virt_code_region = virt_code_region(); generic_mmu::kernel_add_mapping_record( "Kernel code and RO data", &virt_code_region, &kernel_virt_to_phys_region(virt_code_region), &kernel_page_attributes(virt_code_region.start_page_addr()), ); let virt_data_region = virt_data_region(); generic_mmu::kernel_add_mapping_record( "Kernel data and bss", &virt_data_region, &kernel_virt_to_phys_region(virt_data_region), &kernel_page_attributes(virt_data_region.start_page_addr()), ); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! //! The physical memory layout. //! //! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used //! as the boot core's stack. //! //! +---------------------------------------+ //! | | boot_core_stack_start @ 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | data_start == code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | data_end_exclusive //! | | //! //! //! //! //! //! The virtual memory layout is as follows: //! //! +---------------------------------------+ //! | | boot_core_stack_start @ 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | data_start == code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | mmio_remap_start == data_end_exclusive //! | VA region for MMIO remapping | //! | | //! +---------------------------------------+ //! | | mmio_remap_end_exclusive //! | | pub mod mmu; use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // Symbols from the linker script. extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; static __data_start: UnsafeCell<()>; static __data_end_exclusive: UnsafeCell<()>; static __mmio_remap_start: UnsafeCell<()>; static __mmio_remap_end_exclusive: UnsafeCell<()>; static __boot_core_stack_start: UnsafeCell<()>; static __boot_core_stack_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { use super::*; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); pub const PERIPHERAL_IC_SIZE: usize = 0x24; pub const GPIO_START: Address = Address::new(0x3F20_0000); pub const GPIO_SIZE: usize = 0xA0; pub const PL011_UART_START: Address = Address::new(0x3F20_1000); pub const PL011_UART_SIZE: usize = 0x48; pub const END: Address = Address::new(0x4001_0000); } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const GPIO_START: Address = Address::new(0xFE20_0000); pub const GPIO_SIZE: usize = 0xA0; pub const PL011_UART_START: Address = Address::new(0xFE20_1000); pub const PL011_UART_SIZE: usize = 0x48; pub const GICD_START: Address = Address::new(0xFF84_1000); pub const GICD_SIZE: usize = 0x824; pub const GICC_START: Address = Address::new(0xFF84_2000); pub const GICC_SIZE: usize = 0x14; pub const END: Address = Address::new(0xFF85_0000); } pub const END: Address = mmio::END; } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Start page address of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn virt_code_start() -> PageAddress { PageAddress::from(unsafe { __code_start.get() as usize }) } /// Size of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_size() -> usize { unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } } /// Start page address of the data segment. #[inline(always)] fn virt_data_start() -> PageAddress { PageAddress::from(unsafe { __data_start.get() as usize }) } /// Size of the data segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn data_size() -> usize { unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } } /// Start page address of the MMIO remap reservation. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn virt_mmio_remap_start() -> PageAddress { PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) } /// Size of the MMIO remap reservation. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn mmio_remap_size() -> usize { unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } } /// Start page address of the boot core's stack. #[inline(always)] fn virt_boot_core_stack_start() -> PageAddress { PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) } /// Size of the boot core's stack. #[inline(always)] fn boot_core_stack_size() -> usize { unsafe { (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Exclusive end address of the physical address space. #[inline(always)] pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { PageAddress::from(map::END) } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` library. //! //! Used to compose the final kernel binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![allow(incomplete_features)] #![feature(asm_const)] #![feature(const_option)] #![feature(core_intrinsics)] #![feature(format_args_nl)] #![feature(generic_const_exprs)] #![feature(int_roundings)] #![feature(is_sorted)] #![feature(linkage)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(step_trait)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_std] // Testing #![cfg_attr(test, no_main)] #![feature(custom_test_frameworks)] #![reexport_test_harness_main = "test_main"] #![test_runner(crate::test_runner)] mod panic_wait; mod synchronization; pub mod bsp; pub mod common; pub mod console; pub mod cpu; pub mod driver; pub mod exception; pub mod memory; pub mod print; pub mod state; pub mod time; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Version string. pub fn version() -> &'static str { concat!( env!("CARGO_PKG_NAME"), " version ", env!("CARGO_PKG_VERSION") ) } #[cfg(not(test))] extern "Rust" { fn kernel_init() -> !; } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- /// The default runner for unit tests. pub fn test_runner(tests: &[&test_types::UnitTest]) { // This line will be printed as the test header. println!("Running {} tests", tests.len()); for (i, test) in tests.iter().enumerate() { print!("{:>3}. {:.<58}", i + 1, test.name); // Run the actual test. (test.test_func)(); // Failed tests call panic!(). Execution reaches here only if the test has passed. println!("[ok]") } } /// The `kernel_init()` for unit tests. #[cfg(test)] #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); memory::init(); bsp::driver::qemu_bring_up_console(); test_main(); cpu::qemu_exit_success() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/main.rs ================================================ // 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(); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/mapping_record.rs ================================================ // 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()); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/page_alloc.rs ================================================ // 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) } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Translation table. #[cfg(target_arch = "aarch64")] #[path = "../../_arch/aarch64/memory/mmu/translation_table.rs"] mod arch_translation_table; use super::{AttributeFields, MemoryRegion}; use crate::memory::{Address, Physical, Virtual}; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- #[cfg(target_arch = "aarch64")] pub use arch_translation_table::FixedSizeTranslationTable; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Translation table interfaces. pub mod interface { use crate::memory::mmu::PageAddress; use super::*; /// Translation table operations. pub trait TranslationTable { /// Anything that needs to run before any of the other provided functions can be used. /// /// # Safety /// /// - Implementor must ensure that this function can run only once or is harmless if invoked /// multiple times. fn init(&mut self) -> Result<(), &'static str>; /// Map the given virtual memory region to the given physical memory region. /// /// # Safety /// /// - Using wrong attributes can cause multiple issues of different nature in the system. /// - It is not required that the architectural implementation prevents aliasing. That is, /// mapping to the same physical memory using multiple virtual addresses, which would /// break Rust's ownership assumptions. This should be protected against in the kernel's /// generic MMU code. unsafe fn map_at( &mut self, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str>; /// Try to translate a virtual page address to a physical page address. /// /// Will only succeed if there exists a valid mapping for the input page. fn try_virt_page_addr_to_phys_page_addr( &self, virt_page_addr: PageAddress, ) -> Result, &'static str>; /// Try to get the attributes of a page. /// /// Will only succeed if there exists a valid mapping for the input page. fn try_page_attributes( &self, virt_page_addr: PageAddress, ) -> Result; /// Try to translate a virtual address to a physical address. /// /// Will only succeed if there exists a valid mapping for the input address. fn try_virt_addr_to_phys_addr( &self, virt_addr: Address, ) -> Result, &'static str>; } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use crate::memory::mmu::{AccessPermissions, MemAttributes, PageAddress}; use arch_translation_table::MinSizeTranslationTable; use interface::TranslationTable; use test_macros::kernel_test; /// Sanity checks for the TranslationTable implementation. #[kernel_test] fn translationtable_implementation_sanity() { // This will occupy a lot of space on the stack. let mut tables = MinSizeTranslationTable::new_for_runtime(); assert_eq!(tables.init(), Ok(())); let virt_start_page_addr: PageAddress = PageAddress::from(0); let virt_end_exclusive_page_addr: PageAddress = virt_start_page_addr.checked_offset(5).unwrap(); let phys_start_page_addr: PageAddress = PageAddress::from(0); let phys_end_exclusive_page_addr: PageAddress = phys_start_page_addr.checked_offset(5).unwrap(); let virt_region = MemoryRegion::new(virt_start_page_addr, virt_end_exclusive_page_addr); let phys_region = MemoryRegion::new(phys_start_page_addr, phys_end_exclusive_page_addr); let attr = AttributeFields { mem_attributes: MemAttributes::CacheableDRAM, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }; unsafe { assert_eq!(tables.map_at(&virt_region, &phys_region, &attr), Ok(())) }; assert_eq!( tables.try_virt_page_addr_to_phys_page_addr(virt_start_page_addr), Ok(phys_start_page_addr) ); assert_eq!( tables.try_page_attributes(virt_start_page_addr.checked_offset(6).unwrap()), Err("Page marked invalid") ); assert_eq!(tables.try_page_attributes(virt_start_page_addr), Ok(attr)); let virt_addr = virt_start_page_addr.into_inner() + 0x100; let phys_addr = phys_start_page_addr.into_inner() + 0x100; assert_eq!(tables.try_virt_addr_to_phys_addr(virt_addr), Ok(phys_addr)); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit types. use crate::{ bsp, common, memory::{Address, AddressType, Physical}, }; use core::{convert::From, iter::Step, num::NonZeroUsize, ops::Range}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// A wrapper type around [Address] that ensures page alignment. #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct PageAddress { inner: Address, } /// A type that describes a region of memory in quantities of pages. #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct MemoryRegion { start: PageAddress, end_exclusive: PageAddress, } /// Architecture agnostic memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum MemAttributes { CacheableDRAM, Device, } /// Architecture agnostic access permissions. #[allow(missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub enum AccessPermissions { ReadOnly, ReadWrite, } /// Collection of memory attributes. #[allow(missing_docs)] #[derive(Copy, Clone, Debug, Eq, PartialOrd, PartialEq)] pub struct AttributeFields { pub mem_attributes: MemAttributes, pub acc_perms: AccessPermissions, pub execute_never: bool, } /// An MMIO descriptor for use in device drivers. #[derive(Copy, Clone)] pub struct MMIODescriptor { start_addr: Address, end_addr_exclusive: Address, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------ // PageAddress //------------------------------------------------------------------------------ impl PageAddress { /// Unwraps the value. pub fn into_inner(self) -> Address { self.inner } /// Calculates the offset from the page address. /// /// `count` is in units of [PageAddress]. For example, a count of 2 means `result = self + 2 * /// page_size`. pub fn checked_offset(self, count: isize) -> Option { if count == 0 { return Some(self); } let delta = count .unsigned_abs() .checked_mul(bsp::memory::mmu::KernelGranule::SIZE)?; let result = if count.is_positive() { self.inner.as_usize().checked_add(delta)? } else { self.inner.as_usize().checked_sub(delta)? }; Some(Self { inner: Address::new(result), }) } } impl From for PageAddress { fn from(addr: usize) -> Self { assert!( common::is_aligned(addr, bsp::memory::mmu::KernelGranule::SIZE), "Input usize not page aligned" ); Self { inner: Address::new(addr), } } } impl From> for PageAddress { fn from(addr: Address) -> Self { assert!(addr.is_page_aligned(), "Input Address not page aligned"); Self { inner: addr } } } impl Step for PageAddress { fn steps_between(start: &Self, end: &Self) -> Option { if start > end { return None; } // Since start <= end, do unchecked arithmetic. Some( (end.inner.as_usize() - start.inner.as_usize()) >> bsp::memory::mmu::KernelGranule::SHIFT, ) } fn forward_checked(start: Self, count: usize) -> Option { start.checked_offset(count as isize) } fn backward_checked(start: Self, count: usize) -> Option { start.checked_offset(-(count as isize)) } } //------------------------------------------------------------------------------ // MemoryRegion //------------------------------------------------------------------------------ impl MemoryRegion { /// Create an instance. pub fn new(start: PageAddress, end_exclusive: PageAddress) -> Self { assert!(start <= end_exclusive); Self { start, end_exclusive, } } fn as_range(&self) -> Range> { self.into_iter() } /// Returns the start page address. pub fn start_page_addr(&self) -> PageAddress { self.start } /// Returns the start address. pub fn start_addr(&self) -> Address { self.start.into_inner() } /// Returns the exclusive end page address. pub fn end_exclusive_page_addr(&self) -> PageAddress { self.end_exclusive } /// Returns the exclusive end page address. pub fn end_inclusive_page_addr(&self) -> PageAddress { self.end_exclusive.checked_offset(-1).unwrap() } /// Checks if self contains an address. pub fn contains(&self, addr: Address) -> bool { let page_addr = PageAddress::from(addr.align_down_page()); self.as_range().contains(&page_addr) } /// Checks if there is an overlap with another memory region. pub fn overlaps(&self, other_region: &Self) -> bool { let self_range = self.as_range(); self_range.contains(&other_region.start_page_addr()) || self_range.contains(&other_region.end_inclusive_page_addr()) } /// Returns the number of pages contained in this region. pub fn num_pages(&self) -> usize { PageAddress::steps_between(&self.start, &self.end_exclusive).unwrap() } /// Returns the size in bytes of this region. pub fn size(&self) -> usize { // Invariant: start <= end_exclusive, so do unchecked arithmetic. let end_exclusive = self.end_exclusive.into_inner().as_usize(); let start = self.start.into_inner().as_usize(); end_exclusive - start } /// Splits the MemoryRegion like: /// /// -------------------------------------------------------------------------------- /// | | | | | | | | | | | | | | | | | | | /// -------------------------------------------------------------------------------- /// ^ ^ ^ /// | | | /// left_start left_end_exclusive | /// | /// ^ | /// | | /// right_start right_end_exclusive /// /// Left region is returned to the caller. Right region is the new region for this struct. pub fn take_first_n_pages(&mut self, num_pages: NonZeroUsize) -> Result { let count: usize = num_pages.into(); let left_end_exclusive = self.start.checked_offset(count as isize); let left_end_exclusive = match left_end_exclusive { None => return Err("Overflow while calculating left_end_exclusive"), Some(x) => x, }; if left_end_exclusive > self.end_exclusive { return Err("Not enough free pages"); } let allocation = Self { start: self.start, end_exclusive: left_end_exclusive, }; self.start = left_end_exclusive; Ok(allocation) } } impl IntoIterator for MemoryRegion { type Item = PageAddress; type IntoIter = Range; fn into_iter(self) -> Self::IntoIter { Range { start: self.start, end: self.end_exclusive, } } } impl From for MemoryRegion { fn from(desc: MMIODescriptor) -> Self { let start = PageAddress::from(desc.start_addr.align_down_page()); let end_exclusive = PageAddress::from(desc.end_addr_exclusive().align_up_page()); Self { start, end_exclusive, } } } //------------------------------------------------------------------------------ // MMIODescriptor //------------------------------------------------------------------------------ impl MMIODescriptor { /// Create an instance. pub const fn new(start_addr: Address, size: usize) -> Self { assert!(size > 0); let end_addr_exclusive = Address::new(start_addr.as_usize() + size); Self { start_addr, end_addr_exclusive, } } /// Return the start address. pub const fn start_addr(&self) -> Address { self.start_addr } /// Return the exclusive end address. pub fn end_addr_exclusive(&self) -> Address { self.end_addr_exclusive } } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use crate::memory::Virtual; use test_macros::kernel_test; /// Sanity of [PageAddress] methods. #[kernel_test] fn pageaddress_type_method_sanity() { let page_addr: PageAddress = PageAddress::from(bsp::memory::mmu::KernelGranule::SIZE * 2); assert_eq!( page_addr.checked_offset(-2), Some(PageAddress::::from(0)) ); assert_eq!( page_addr.checked_offset(2), Some(PageAddress::::from( bsp::memory::mmu::KernelGranule::SIZE * 4 )) ); assert_eq!( PageAddress::::from(0).checked_offset(0), Some(PageAddress::::from(0)) ); assert_eq!(PageAddress::::from(0).checked_offset(-1), None); let max_page_addr = Address::::new(usize::MAX).align_down_page(); assert_eq!( PageAddress::::from(max_page_addr).checked_offset(1), None ); let zero = PageAddress::::from(0); let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); assert_eq!(PageAddress::steps_between(&zero, &three), Some(3)); } /// Sanity of [MemoryRegion] methods. #[kernel_test] fn memoryregion_type_method_sanity() { let zero = PageAddress::::from(0); let zero_region = MemoryRegion::new(zero, zero); assert_eq!(zero_region.num_pages(), 0); assert_eq!(zero_region.size(), 0); let one = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE); let one_region = MemoryRegion::new(zero, one); assert_eq!(one_region.num_pages(), 1); assert_eq!(one_region.size(), bsp::memory::mmu::KernelGranule::SIZE); let three = PageAddress::::from(bsp::memory::mmu::KernelGranule::SIZE * 3); let mut three_region = MemoryRegion::new(zero, three); assert!(three_region.contains(zero.into_inner())); assert!(!three_region.contains(three.into_inner())); assert!(three_region.overlaps(&one_region)); let allocation = three_region .take_first_n_pages(NonZeroUsize::new(2).unwrap()) .unwrap(); assert_eq!(allocation.num_pages(), 2); assert_eq!(three_region.num_pages(), 1); for (i, alloc) in allocation.into_iter().enumerate() { assert_eq!( alloc.into_inner().as_usize(), i * bsp::memory::mmu::KernelGranule::SIZE ); } } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Memory Management Unit. #[cfg(target_arch = "aarch64")] #[path = "../_arch/aarch64/memory/mmu.rs"] mod arch_mmu; mod mapping_record; mod page_alloc; mod translation_table; mod types; use crate::{ bsp, memory::{Address, Physical, Virtual}, synchronization::{self, interface::Mutex}, warn, }; use core::{fmt, num::NonZeroUsize}; pub use types::*; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// MMU enable errors variants. #[allow(missing_docs)] #[derive(Debug)] pub enum MMUEnableError { AlreadyEnabled, Other(&'static str), } /// Memory Management interfaces. pub mod interface { use super::*; /// MMU functions. pub trait MMU { /// Turns on the MMU for the first time and enables data and instruction caching. /// /// # Safety /// /// - Changes the HW's global state. unsafe fn enable_mmu_and_caching( &self, phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError>; /// Returns true if the MMU is enabled, false otherwise. fn is_enabled(&self) -> bool; } } /// Describes the characteristics of a translation granule. pub struct TranslationGranule; /// Describes properties of an address space. pub struct AddressSpace; /// Intended to be implemented for [`AddressSpace`]. pub trait AssociatedTranslationTable { /// A translation table whose address range is: /// /// [AS_SIZE - 1, 0] type TableStartFromBottom; } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- use interface::MMU; use synchronization::interface::ReadWriteEx; use translation_table::interface::TranslationTable; /// Map a region in the kernel's translation tables. /// /// No input checks done, input is passed through to the architectural implementation. /// /// # Safety /// /// - See `map_at()`. /// - Does not prevent aliasing. unsafe fn kernel_map_at_unchecked( name: &'static str, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) -> Result<(), &'static str> { bsp::memory::mmu::kernel_translation_tables() .write(|tables| tables.map_at(virt_region, phys_region, attr))?; kernel_add_mapping_record(name, virt_region, phys_region, attr); Ok(()) } /// Try to translate a kernel virtual address to a physical address. /// /// Will only succeed if there exists a valid mapping for the input address. fn try_kernel_virt_addr_to_phys_addr( virt_addr: Address, ) -> Result, &'static str> { bsp::memory::mmu::kernel_translation_tables() .read(|tables| tables.try_virt_addr_to_phys_addr(virt_addr)) } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl fmt::Display for MMUEnableError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MMUEnableError::AlreadyEnabled => write!(f, "MMU is already enabled"), MMUEnableError::Other(x) => write!(f, "{}", x), } } } impl TranslationGranule { /// The granule's size. pub const SIZE: usize = Self::size_checked(); /// The granule's mask. pub const MASK: usize = Self::SIZE - 1; /// The granule's shift, aka log2(size). pub const SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(GRANULE_SIZE.is_power_of_two()); GRANULE_SIZE } } impl AddressSpace { /// The address space size. pub const SIZE: usize = Self::size_checked(); /// The address space shift, aka log2(size). pub const SIZE_SHIFT: usize = Self::SIZE.trailing_zeros() as usize; const fn size_checked() -> usize { assert!(AS_SIZE.is_power_of_two()); // Check for architectural restrictions as well. Self::arch_address_space_size_sanity_checks(); AS_SIZE } } /// Query the BSP for the reserved virtual addresses for MMIO remapping and initialize the kernel's /// MMIO VA allocator with it. pub fn kernel_init_mmio_va_allocator() { let region = bsp::memory::mmu::virt_mmio_remap_region(); page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.init(region)); } /// Add an entry to the mapping info record. pub fn kernel_add_mapping_record( name: &'static str, virt_region: &MemoryRegion, phys_region: &MemoryRegion, attr: &AttributeFields, ) { if let Err(x) = mapping_record::kernel_add(name, virt_region, phys_region, attr) { warn!("{}", x); } } /// MMIO remapping in the kernel translation tables. /// /// Typically used by device drivers. /// /// # Safety /// /// - Same as `kernel_map_at_unchecked()`, minus the aliasing part. pub unsafe fn kernel_map_mmio( name: &'static str, mmio_descriptor: &MMIODescriptor, ) -> Result, &'static str> { let phys_region = MemoryRegion::from(*mmio_descriptor); let offset_into_start_page = mmio_descriptor.start_addr().offset_into_page(); // Check if an identical region has been mapped for another driver. If so, reuse it. let virt_addr = if let Some(addr) = mapping_record::kernel_find_and_insert_mmio_duplicate(mmio_descriptor, name) { addr // Otherwise, allocate a new region and map it. } else { let num_pages = match NonZeroUsize::new(phys_region.num_pages()) { None => return Err("Requested 0 pages"), Some(x) => x, }; let virt_region = page_alloc::kernel_mmio_va_allocator().lock(|allocator| allocator.alloc(num_pages))?; kernel_map_at_unchecked( name, &virt_region, &phys_region, &AttributeFields { mem_attributes: MemAttributes::Device, acc_perms: AccessPermissions::ReadWrite, execute_never: true, }, )?; virt_region.start_addr() }; Ok(virt_addr + offset_into_start_page) } /// Try to translate a kernel virtual page address to a physical page address. /// /// Will only succeed if there exists a valid mapping for the input page. pub fn try_kernel_virt_page_addr_to_phys_page_addr( virt_page_addr: PageAddress, ) -> Result, &'static str> { bsp::memory::mmu::kernel_translation_tables() .read(|tables| tables.try_virt_page_addr_to_phys_page_addr(virt_page_addr)) } /// Try to get the attributes of a kernel page. /// /// Will only succeed if there exists a valid mapping for the input page. pub fn try_kernel_page_attributes( virt_page_addr: PageAddress, ) -> Result { bsp::memory::mmu::kernel_translation_tables() .read(|tables| tables.try_page_attributes(virt_page_addr)) } /// Human-readable print of all recorded kernel mappings. pub fn kernel_print_mappings() { mapping_record::kernel_print() } /// Enable the MMU and data + instruction caching. /// /// # Safety /// /// - Crucial function during kernel init. Changes the the complete memory view of the processor. #[inline(always)] pub unsafe fn enable_mmu_and_caching( phys_tables_base_addr: Address, ) -> Result<(), MMUEnableError> { arch_mmu::mmu().enable_mmu_and_caching(phys_tables_base_addr) } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/memory.rs ================================================ // 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); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/00_console_sanity.rs ================================================ // 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(); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/01_timer_sanity.rs ================================================ // 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) } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2019-2023 Andre Richter //! Page faults must result in synchronous exceptions. #![feature(format_args_nl)] #![no_main] #![no_std] /// Overwrites libkernel's `panic_wait::_panic_exit()` so that it returns a "success" code. /// /// In this test, reaching the panic is a success, because it is called from the synchronous /// exception handler, which is what this test wants to achieve. /// /// It also means that this integration test can not use any other code that calls panic!() directly /// or indirectly. mod panic_exit_success; use libkernel::{bsp, cpu, exception, info, memory, println}; #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); memory::init(); bsp::driver::qemu_bring_up_console(); // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); info!("Writing beyond mapped area to address 9 GiB..."); let big_addr: u64 = 9 * 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); // If execution reaches here, the memory access above did not cause a page fault exception. cpu::qemu_exit_failure() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/03_exception_restore_sanity.rs ================================================ // 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(); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/04_exception_irq_sanity.rs ================================================ // 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()); } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField def initialize @value = 0 end def self.attr_bitfield(name, offset, num_bits) define_method("#{name}=") do |bits| mask = (2**num_bits) - 1 raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? # Clear bitfield @value &= ~(mask << offset) # Set it @value |= (bits << offset) end end def to_i @value end def size_in_byte 8 end end # An array class that knows its memory location. class CArray < Array attr_reader :phys_start_addr def initialize(phys_start_addr, size, &block) @phys_start_addr = phys_start_addr super(size, &block) end def size_in_byte inject(0) { |sum, n| sum + n.size_in_byte } end end #--------------------------------------------------------------------------------------------------- # Arch:: #--------------------------------------------------------------------------------------------------- module Arch #--------------------------------------------------------------------------------------------------- # Arch::ARMv8 #--------------------------------------------------------------------------------------------------- module ARMv8 # ARMv8 Table Descriptor. class Stage1TableDescriptor < BitField module NextLevelTableAddr OFFSET = 16 NUMBITS = 32 end module Type OFFSET = 1 NUMBITS = 1 BLOCK = 0 TABLE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def next_level_table_addr=(addr) addr >>= Granule64KiB::SHIFT self.__next_level_table_addr = addr end private :__next_level_table_addr= end # ARMv8 level 3 page descriptor. class Stage1PageDescriptor < BitField module UXN OFFSET = 54 NUMBITS = 1 FALSE = 0 TRUE = 1 end module PXN OFFSET = 53 NUMBITS = 1 FALSE = 0 TRUE = 1 end module OutputAddr OFFSET = 16 NUMBITS = 32 end module AF OFFSET = 10 NUMBITS = 1 FALSE = 0 TRUE = 1 end module SH OFFSET = 8 NUMBITS = 2 INNER_SHAREABLE = 0b11 end module AP OFFSET = 6 NUMBITS = 2 RW_EL1 = 0b00 RO_EL1 = 0b10 end module AttrIndx OFFSET = 2 NUMBITS = 3 end module Type OFFSET = 1 NUMBITS = 1 RESERVED_INVALID = 0 PAGE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def output_addr=(addr) addr >>= Granule64KiB::SHIFT self.__output_addr = addr end private :__output_addr= end # Translation table representing the structure defined in translation_table.rs. class TranslationTable module MAIR NORMAL = 1 end def initialize do_sanity_checks num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) populate_lvl2_entries end def map_at(virt_region, phys_region, attributes) return if virt_region.empty? raise if virt_region.size != phys_region.size raise if phys_region.last > BSP.phys_addr_space_end_page virt_region.zip(phys_region).each do |virt_page, phys_page| desc = page_descriptor_from(virt_page) set_lvl3_entry(desc, phys_page, attributes) end end def to_binary data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) data.pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr_binary [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr @lvl2_phys_start_addr end private def do_sanity_checks raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? end def new_lvl3(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do temp = CArray.new(start_addr, 8192) do Stage1PageDescriptor.new end start_addr += temp.size_in_byte temp end end def new_lvl2(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do Stage1TableDescriptor.new end end def populate_lvl2_entries @lvl2.each_with_index do |descriptor, i| descriptor.next_level_table_addr = @lvl3[i].phys_start_addr descriptor.type = Stage1TableDescriptor::Type::TABLE descriptor.valid = Stage1TableDescriptor::Valid::TRUE end end def lvl2_lvl3_index_from(addr) lvl2_index = addr >> Granule512MiB::SHIFT lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT raise unless lvl2_index < @lvl2.size [lvl2_index, lvl3_index] end def page_descriptor_from(virt_addr) lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) @lvl3[lvl2_index][lvl3_index] end # rubocop:disable Metrics/MethodLength def set_attributes(desc, attributes) case attributes.mem_attributes when :CacheableDRAM desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE desc.attr_indx = MAIR::NORMAL else raise 'Invalid input' end desc.ap = case attributes.acc_perms when :ReadOnly Stage1PageDescriptor::AP::RO_EL1 when :ReadWrite Stage1PageDescriptor::AP::RW_EL1 else raise 'Invalid input' end desc.pxn = if attributes.execute_never Stage1PageDescriptor::PXN::TRUE else Stage1PageDescriptor::PXN::FALSE end desc.uxn = Stage1PageDescriptor::UXN::TRUE end # rubocop:enable Metrics/MethodLength def set_lvl3_entry(desc, output_addr, attributes) desc.output_addr = output_addr desc.af = Stage1PageDescriptor::AF::TRUE desc.type = Stage1PageDescriptor::Type::PAGE desc.valid = Stage1PageDescriptor::Valid::TRUE set_attributes(desc, attributes) end end end end ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter # Raspberry Pi 3 + 4 class RaspberryPi attr_reader :kernel_granule, :kernel_virt_addr_space_size MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") def initialize @kernel_granule = Granule64KiB @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( 'PHYS_KERNEL_TABLES_BASE_ADDR' ) end def phys_addr_of_kernel_tables KERNEL_ELF.virt_to_phys(@virt_addr_of_kernel_tables) end def kernel_tables_offset_in_file KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_kernel_tables) end def phys_kernel_tables_base_addr_offset_in_file KERNEL_ELF.virt_addr_to_file_offset(@virt_addr_of_phys_kernel_tables_base_addr) end def phys_addr_space_end_page x = MEMORY_SRC.grep(/pub const END/) x = case BSP_TYPE when :rpi3 x[0] when :rpi4 x[1] else raise end x.scan(/\d+/).join.to_i(16) end end ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/generic.rb ================================================ # 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 ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/main.rb ================================================ #!/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" ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel" ] [profile.release] lto = true ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 # Optional integration test name. ifdef TEST TEST_ARG = --test $(TEST) else TEST_ARG = --test '*' endif ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi3.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi3.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none QEMU_TEST_ARGS = $(QEMU_RELEASE_ARGS) -semihosting OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf OPENOCD_ARG = -f /openocd/tcl/interface/ftdi/olimex-arm-usb-tiny-h.cfg -f /openocd/rpi4.cfg JTAG_BOOT_IMAGE = ../X1_JTAG_boot/jtag_boot_rpi4.img LD_SCRIPT_PATH = $(shell pwd)/kernel/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = kernel/Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF_RAW = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_RAW_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF_RAW).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Translation tables ##------------------------------------------------------------------------------ TT_TOOL_PATH = tools/translation_table_tool KERNEL_ELF_TTABLES = target/$(TARGET)/release/kernel+ttables KERNEL_ELF_TTABLES_DEPS = $(KERNEL_ELF_RAW) $(wildcard $(TT_TOOL_PATH)/*) KERNEL_ELF = $(KERNEL_ELF_TTABLES) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) TEST_CMD = cargo test $(COMPILER_ARGS) --manifest-path $(KERNEL_MANIFEST) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TT_TOOL = ruby $(TT_TOOL_PATH)/main.rb EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DIR_JTAG = -v $(shell pwd)/../X1_JTAG_boot:/work/X1_JTAG_boot DOCKER_ARG_DEV = --privileged -v /dev:/dev DOCKER_ARG_NET = --network host # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_GDB = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) DOCKER_JTAGBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_ARG_DIR_JTAG) $(DOCKER_IMAGE) DOCKER_OPENOCD = $(DOCKER_CMD_DEV) $(DOCKER_ARG_NET) $(DOCKER_IMAGE) else DOCKER_OPENOCD = echo "Not yet supported on non-Linux systems."; \# endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF_RAW): $(KERNEL_ELF_RAW_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Precompute the kernel translation tables and patch them into the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF_TTABLES): $(KERNEL_ELF_TTABLES_DEPS) $(call color_header, "Precomputing kernel translation tables and patching kernel ELF") @cp $(KERNEL_ELF_RAW) $(KERNEL_ELF_TTABLES) @$(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $(KERNEL_ELF_TTABLES) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF_TTABLES) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF_TTABLES) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) --features test_build --tests \ --manifest-path $(KERNEL_MANIFEST) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Debugging targets ##-------------------------------------------------------------------------------------------------- .PHONY: jtagboot openocd gdb gdb-opt0 ##------------------------------------------------------------------------------ ## Push the JTAG boot image to the real HW target ##------------------------------------------------------------------------------ jtagboot: @$(DOCKER_JTAGBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(JTAG_BOOT_IMAGE) ##------------------------------------------------------------------------------ ## Start OpenOCD session ##------------------------------------------------------------------------------ openocd: $(call color_header, "Launching OpenOCD") @$(DOCKER_OPENOCD) openocd $(OPENOCD_ARG) ##------------------------------------------------------------------------------ ## Start GDB session ##------------------------------------------------------------------------------ gdb: RUSTC_MISC_ARGS += -C debuginfo=2 gdb-opt0: RUSTC_MISC_ARGS += -C debuginfo=2 -C opt-level=0 gdb gdb-opt0: $(KERNEL_ELF) $(call color_header, "Launching GDB") @$(DOCKER_GDB) gdb-multiarch -q $(KERNEL_ELF) ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot test_unit test_integration test_unit test_integration: FEATURES += --features test_build ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test_unit test_integration test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Helpers for unit and integration test targets ##------------------------------------------------------------------------------ define KERNEL_TEST_RUNNER #!/usr/bin/env bash # The cargo test runner seems to change into the crate under test's directory. Therefore, ensure # this script executes from the root. cd $(shell pwd) TEST_ELF=$$(echo $$1 | sed -e 's/.*target/target/g') TEST_BINARY=$$(echo $$1.img | sed -e 's/.*target/target/g') $(DOCKER_TOOLS) $(EXEC_TT_TOOL) $(BSP) $$TEST_ELF > /dev/null $(OBJCOPY_CMD) $$TEST_ELF $$TEST_BINARY $(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_TEST_ARGS) -kernel $$TEST_BINARY endef export KERNEL_TEST_RUNNER define test_prepare @mkdir -p target @echo "$$KERNEL_TEST_RUNNER" > target/kernel_test_runner.sh @chmod +x target/kernel_test_runner.sh endef ##------------------------------------------------------------------------------ ## Run unit test(s) ##------------------------------------------------------------------------------ test_unit: $(call color_header, "Compiling unit test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) --lib ##------------------------------------------------------------------------------ ## Run integration test(s) ##------------------------------------------------------------------------------ test_integration: $(call color_header, "Compiling integration test(s) - $(BSP)") $(call test_prepare) @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(TEST_CMD) $(TEST_ARG) test: test_boot test_unit test_integration endif ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/README.md ================================================ # Tutorial 16 - Virtual Memory Part 4: Higher-Half Kernel ## tl;dr - The time has come: We map and run the kernel from the top of the 64 bit virtual address space! 🥳 ## Table of Contents - [Introduction](#introduction) - [Implementation](#implementation) - [Linking Changes](#linking-changes) - [Position-Independent Boot Code](#position-independent-boot-code) - [Test it](#test-it) - [Diff to previous](#diff-to-previous) ## Introduction A long time in the making, in this tutorial we finally map the kernel to the most significant area (alternatively: higher-half) of the 64 bit virtual address space. This makes room for future applications to use the whole of the least significant area of the virtual memory space. As has been teased since `tutorial 14`, we will make use of the `AArch64`'s `TTBR1`. Since the kernel's virtual address space size currently is `1 GiB` (defined in `bsp/__board_name__/memory/mmu.rs`), `TTBR1` will cover the range from `0xffff_ffff_ffff_ffff` down to `ffff_ffff_c000_0000` (both inclusive). ## Implementation In `src/memory/mmu.rs`, we extend the `AssociatedTranslationTable` trait with a `TableStartFromTop` associated type: ```rust /// Intended to be implemented for [`AddressSpace`]. pub trait AssociatedTranslationTable { /// A translation table whose address range is: /// /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] type TableStartFromTop; /// A translation table whose address range is: /// /// [AS_SIZE - 1, 0] type TableStartFromBottom; } ``` Architecture specific code in `_arch/aarch64/memory/mmu/translation_table.rs` populates both types now by making use of a new generic that is added to `FixedSizeTranslationTable`, which defines whether the covered address space starts from the top or the bottom: ```rust pub struct FixedSizeTranslationTable { ... ``` ```rust impl memory::mmu::AssociatedTranslationTable for memory::mmu::AddressSpace where [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, { type TableStartFromTop = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; } ``` Thanks to this infrastructure, `BSP` Rust code in `bsp/__board_name__/memory/mmu.rs` only needs to change to this newly introduced type in order to switch from lower half to higher half translation tables for the kernel: ```rust type KernelTranslationTable = ::TableStartFromTop; ``` ### Linking Changes In the `kernel.ld` linker script, we define a new symbol `__kernel_virt_start_addr` now, which is the start address of the kernel's virtual address space, calculated as `(u64::MAX - __kernel_virt_addr_space_size) + 1`. Before the first section definition, we set the linker script's location counter to this address: ```ld.s SECTIONS { . = __kernel_virt_start_addr; ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ ``` Since we are not identity mapping anymore, we start to make use of the `AT` keyword in the output section specification: ```ld.s /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; /* omitted */ SECTIONS { . = __kernel_virt_start_addr; /* omitted */ __code_start = .; .text : AT(__rpi_phys_binary_load_addr) ``` This will manifest in the kernel ELF `segment` attributes, as can be inspected using the `make readelf` command: ```console $ make readelf Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flags Align LOAD 0x0000000000010000 0xffffffffc0000000 0x0000000000080000 0x000000000000cb08 0x000000000000cb08 R E 0x10000 LOAD 0x0000000000020000 0xffffffffc0010000 0x0000000000090000 0x0000000000030dc0 0x0000000000030de0 RW 0x10000 LOAD 0x0000000000060000 0xffffffffc0860000 0x0000000000000000 0x0000000000000000 0x0000000000080000 RW 0x10000 Section to Segment mapping: Segment Sections... 00 .text .rodata 01 .data .bss 02 .boot_core_stack ``` As you can see, `VirtAddr` and `PhysAddr` are different now, as compared to all the previous tutorials where they were identical. This information from the `ELF` file will eventually be parsed by the `translation table tool` and incorporated when compiling the precomputed translation tables. You might have noticed that `.text .rodata` and `.boot_core_stack` exchanged places as compared to previous tutorials. The reason this was done is that with a remapped kernel, this is trivial to do without affecting the physical layout. This allows us to place an unmapped `guard page` between the `boot core stack` and the `mmio remap region` in the VA space, which nicely protects the kernel from stack overflows now: ```ld.s /*********************************************************************************************** * MMIO Remap Reserved ***********************************************************************************************/ __mmio_remap_start = .; . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") /*********************************************************************************************** * Guard Page ***********************************************************************************************/ . += PAGE_SIZE; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) { __boot_core_stack_start = .; /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") ``` Changes in the `_arch` `MMU` driver are minimal, and mostly concerned with configuring `TCR_EL1` for use with `TTBR1_EL1` now. And of course, setting `TTBR1_EL1` in `fn enable_mmu_and_caching(...)`. ### Position-Independent Boot Code Remember all the fuss that we made about `position-independent code` that will be needed until the `MMU` is enabled. Let's quickly check what it means for us in reality now: In `_arch/aarch64/cpu/boot.rs`, we turn on the `MMU` just before returning from `EL2` to `EL1`. So by the time the CPU enters `EL1`, virtual memory will be active, and the CPU must therefore use the new higher-half `virtual addresses` for everything it does. Specifically, this means the address from which the CPU should execute upon entering `EL1` (function `kernel_init()`) must be a valid _virtual address_, same as the stack pointer's address. Both of them are programmed in function `fn prepare_el2_to_el1_transition(...)`, so we must ensure now that _link-time_ addresses are used here. For this reason, retrieval of these addresses happens in `assembly` in `boot.s`, where we can explicitly enforce generation of **absolute** addresses: ```asm // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at // the top of the 64 bit address space, these are effectively virtual addresses. ADR_ABS x1, __boot_core_stack_end_exclusive ADR_ABS x2, kernel_init ``` Both values are forwarded to the Rust entry point function `_start_rust()`, which in turn forwards them to `fn prepare_el2_to_el1_transition(...)`. One more thing to consider is that we keep on programming the boot core's stack address for `EL2` using an address that is calculated `PC-relative`, because all the `EL2` code will still run while virtual memory _is disabled_. As such, we need the "physical" address of the stack, so to speak. The previous tutorial also explained that it is not easily possible to compile select files using `-fpic` in `Rust`. Still, we are doing some function calls in `Rust` before virtual memory is enabled, so _theoretically_, there is room for failure. However, branches to local code in `AArch64` are usually generated PC-relative. So it is a small risk worth taking. Should it still fail someday, at least our automated CI pipeline would give notice when the tests start to fail. ## Test it That's it! We are ready for a higher-half kernel now. Power up your Raspberrys and marvel at those beautiful (virtual) addresses: Raspberry Pi 3: ```console $ make chainboot [...] Precomputing kernel translation tables and patching kernel ELF ------------------------------------------------------------------------------------ Sections Virt Start Addr Phys Start Addr Size Attr ------------------------------------------------------------------------------------ Generating .text .rodata | 0xffff_ffff_c000_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X Generating .data .bss | 0xffff_ffff_c001_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN Generating .boot_core_stack | 0xffff_ffff_c086_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN ------------------------------------------------------------------------------------ Patching Kernel table struct at ELF file offset 0x2_0000 Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0088 Finished in 0.14s Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 3 [ML] Requesting binary [MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 [ML] Loaded! Executing the payload now [ 2.870248] mingo version 0.16.0 [ 2.870456] Booting on: Raspberry Pi 3 [ 2.870911] MMU online: [ 2.871203] ------------------------------------------------------------------------------------------------------------------------------------------- [ 2.872947] Virtual Physical Size Attr Entity [ 2.874691] ------------------------------------------------------------------------------------------------------------------------------------------- [ 2.876436] 0xffff_ffff_c000_0000..0xffff_ffff_c000_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data [ 2.878050] 0xffff_ffff_c001_0000..0xffff_ffff_c004_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss [ 2.879621] 0xffff_ffff_c005_0000..0xffff_ffff_c005_ffff --> 0x00_3f20_0000..0x00_3f20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART [ 2.881137] | BCM GPIO [ 2.882589] 0xffff_ffff_c006_0000..0xffff_ffff_c006_ffff --> 0x00_3f00_0000..0x00_3f00_ffff | 64 KiB | Dev RW XN | BCM Interrupt Controller [ 2.884214] 0xffff_ffff_c086_0000..0xffff_ffff_c08d_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack [ 2.885818] ------------------------------------------------------------------------------------------------------------------------------------------- ``` Raspberry Pi 4: ```console $ BSP=rpi4 make chainboot [...] Precomputing kernel translation tables and patching kernel ELF ------------------------------------------------------------------------------------ Sections Virt Start Addr Phys Start Addr Size Attr ------------------------------------------------------------------------------------ Generating .text .rodata | 0xffff_ffff_c000_0000 | 0x0000_0000_0008_0000 | 64 KiB | C RO X Generating .data .bss | 0xffff_ffff_c001_0000 | 0x0000_0000_0009_0000 | 256 KiB | C RW XN Generating .boot_core_stack | 0xffff_ffff_c086_0000 | 0x0000_0000_0000_0000 | 512 KiB | C RW XN ------------------------------------------------------------------------------------ Patching Kernel table struct at ELF file offset 0x2_0000 Patching Kernel tables physical base address start argument to value 0xb_0000 at ELF file offset 0x1_0080 Finished in 0.13s Minipush 1.0 [MP] ⏳ Waiting for /dev/ttyUSB0 [MP] ✅ Serial connected [MP] 🔌 Please power the target now __ __ _ _ _ _ | \/ (_)_ _ (_) | ___ __ _ __| | | |\/| | | ' \| | |__/ _ \/ _` / _` | |_| |_|_|_||_|_|____\___/\__,_\__,_| Raspberry Pi 4 [ML] Requesting binary [MP] ⏩ Pushing 257 KiB ======================================🦀 100% 128 KiB/s Time: 00:00:02 [ML] Loaded! Executing the payload now [ 2.871960] mingo version 0.16.0 [ 2.871994] Booting on: Raspberry Pi 4 [ 2.872449] MMU online: [ 2.872742] ------------------------------------------------------------------------------------------------------------------------------------------- [ 2.874486] Virtual Physical Size Attr Entity [ 2.876230] ------------------------------------------------------------------------------------------------------------------------------------------- [ 2.877975] 0xffff_ffff_c000_0000..0xffff_ffff_c000_ffff --> 0x00_0008_0000..0x00_0008_ffff | 64 KiB | C RO X | Kernel code and RO data [ 2.879589] 0xffff_ffff_c001_0000..0xffff_ffff_c004_ffff --> 0x00_0009_0000..0x00_000c_ffff | 256 KiB | C RW XN | Kernel data and bss [ 2.881159] 0xffff_ffff_c005_0000..0xffff_ffff_c005_ffff --> 0x00_fe20_0000..0x00_fe20_ffff | 64 KiB | Dev RW XN | BCM PL011 UART [ 2.882676] | BCM GPIO [ 2.884128] 0xffff_ffff_c006_0000..0xffff_ffff_c006_ffff --> 0x00_ff84_0000..0x00_ff84_ffff | 64 KiB | Dev RW XN | GICv2 GICD [ 2.885601] | GICV2 GICC [ 2.887074] 0xffff_ffff_c086_0000..0xffff_ffff_c08d_ffff --> 0x00_0000_0000..0x00_0007_ffff | 512 KiB | C RW XN | Kernel boot-core stack [ 2.888678] ------------------------------------------------------------------------------------------------------------------------------------------- ``` ## Diff to previous ```diff diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml 16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml --- 15_virtual_mem_part3_precomputed_tables/kernel/Cargo.toml +++ 16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mingo" -version = "0.15.0" +version = "0.16.0" authors = ["Andre Richter "] edition = "2021" diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs @@ -34,7 +34,10 @@ /// - The `bss` section is not initialized yet. The code must not use or reference it in any way. /// - The HW state of EL1 must be prepared in a sound way. #[inline(always)] -unsafe fn prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr: u64) { +unsafe fn prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, +) { // Enable timer counter registers for EL1. CNTHCTL_EL2.write(CNTHCTL_EL2::EL1PCEN::SET + CNTHCTL_EL2::EL1PCTEN::SET); @@ -57,11 +60,11 @@ ); // Second, let the link register point to kernel_init(). - ELR_EL2.set(crate::kernel_init as *const () as u64); + ELR_EL2.set(virt_kernel_init_addr); // Set up SP_EL1 (stack pointer), which will be used by EL1 once we "return" to it. Since there // are no plans to ever return to EL2, just re-use the same stack. - SP_EL1.set(phys_boot_core_stack_end_exclusive_addr); + SP_EL1.set(virt_boot_core_stack_end_exclusive_addr); } //-------------------------------------------------------------------------------------------------- @@ -78,14 +81,19 @@ #[no_mangle] pub unsafe extern "C" fn _start_rust( phys_kernel_tables_base_addr: u64, - phys_boot_core_stack_end_exclusive_addr: u64, + virt_boot_core_stack_end_exclusive_addr: u64, + virt_kernel_init_addr: u64, ) -> ! { - prepare_el2_to_el1_transition(phys_boot_core_stack_end_exclusive_addr); + prepare_el2_to_el1_transition( + virt_boot_core_stack_end_exclusive_addr, + virt_kernel_init_addr, + ); // Turn on the MMU for EL1. let addr = Address::new(phys_kernel_tables_base_addr as usize); memory::mmu::enable_mmu_and_caching(addr).unwrap(); - // Use `eret` to "return" to EL1. This results in execution of kernel_init() in EL1. + // Use `eret` to "return" to EL1. Since virtual memory will already be enabled, this results in + // execution of kernel_init() in EL1 from its _virtual address_. asm::eret() } diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s --- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/cpu/boot.s +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s @@ -18,6 +18,18 @@ add \register, \register, #:lo12:\symbol .endm +// Load the address of a symbol into a register, absolute. +// +// # Resources +// +// - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html +.macro ADR_ABS register, symbol + movz \register, #:abs_g3:\symbol + movk \register, #:abs_g2_nc:\symbol + movk \register, #:abs_g1_nc:\symbol + movk \register, #:abs_g0_nc:\symbol +.endm + //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- @@ -56,19 +68,31 @@ // Load the base address of the kernel's translation tables. ldr x0, PHYS_KERNEL_TABLES_BASE_ADDR // provided by bsp/__board_name__/memory/mmu.rs - // Set the stack pointer. This ensures that any code in EL2 that needs the stack will work. - ADR_REL x1, __boot_core_stack_end_exclusive - mov sp, x1 + // Load the _absolute_ addresses of the following symbols. Since the kernel is linked at + // the top of the 64 bit address space, these are effectively virtual addresses. + ADR_ABS x1, __boot_core_stack_end_exclusive + ADR_ABS x2, kernel_init + + // Load the PC-relative address of the stack and set the stack pointer. + // + // Since _start() is the first function that runs after the firmware has loaded the kernel + // into memory, retrieving this symbol PC-relative returns the "physical" address. + // + // Setting the stack pointer to this value ensures that anything that still runs in EL2, + // until the kernel returns to EL1 with the MMU enabled, works as well. After the return to + // EL1, the virtual address of the stack retrieved above will be used. + ADR_REL x3, __boot_core_stack_end_exclusive + mov sp, x3 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. - ADR_REL x2, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs - mrs x3, CNTFRQ_EL0 - cmp x3, xzr + ADR_REL x4, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs + mrs x5, CNTFRQ_EL0 + cmp x5, xzr b.eq .L_parking_loop - str w3, [x2] + str w5, [x4] - // Jump to Rust code. x0 and x1 hold the function arguments provided to _start_rust(). + // Jump to Rust code. x0, x1 and x2 hold the function arguments provided to _start_rust(). b _start_rust // Infinitely wait for events (aka "park the core"). diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs @@ -136,7 +136,7 @@ /// aligned, so the lvl3 is put first. #[repr(C)] #[repr(align(65536))] -pub struct FixedSizeTranslationTable { +pub struct FixedSizeTranslationTable { /// Page descriptors, covering 64 KiB windows per entry. lvl3: [[PageDescriptor; 8192]; NUM_TABLES], @@ -302,10 +302,19 @@ where [u8; Self::SIZE >> Granule512MiB::SHIFT]: Sized, { - type TableStartFromBottom = FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }>; + type TableStartFromTop = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, true>; + + type TableStartFromBottom = + FixedSizeTranslationTable<{ Self::SIZE >> Granule512MiB::SHIFT }, false>; } -impl FixedSizeTranslationTable { +impl + FixedSizeTranslationTable +{ + const START_FROM_TOP_OFFSET: Address = + Address::new((usize::MAX - (Granule512MiB::SIZE * NUM_TABLES)) + 1); + /// Create an instance. #[allow(clippy::assertions_on_constants)] const fn _new(for_precompute: bool) -> Self { @@ -336,9 +345,14 @@ &self, virt_page_addr: PageAddress, ) -> Result<(usize, usize), &'static str> { - let addr = virt_page_addr.into_inner().as_usize(); - let lvl2_index = addr >> Granule512MiB::SHIFT; - let lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT; + let mut addr = virt_page_addr.into_inner(); + + if START_FROM_TOP { + addr = addr - Self::START_FROM_TOP_OFFSET; + } + + let lvl2_index = addr.as_usize() >> Granule512MiB::SHIFT; + let lvl3_index = (addr.as_usize() & Granule512MiB::MASK) >> Granule64KiB::SHIFT; if lvl2_index > (NUM_TABLES - 1) { return Err("Virtual page is out of bounds of translation table"); @@ -384,8 +398,9 @@ // OS Interface Code //------------------------------------------------------------------------------ -impl memory::mmu::translation_table::interface::TranslationTable - for FixedSizeTranslationTable +impl + memory::mmu::translation_table::interface::TranslationTable + for FixedSizeTranslationTable { fn init(&mut self) -> Result<(), &'static str> { if self.initialized { @@ -479,7 +494,7 @@ //-------------------------------------------------------------------------------------------------- #[cfg(test)] -pub type MinSizeTranslationTable = FixedSizeTranslationTable<1>; +pub type MinSizeTranslationTable = FixedSizeTranslationTable<1, true>; #[cfg(test)] mod tests { diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/_arch/aarch64/memory/mmu.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs @@ -66,6 +66,7 @@ impl MemoryManagementUnit { /// Setup function for the MAIR_EL1 register. + #[inline(always)] fn set_up_mair(&self) { // Define the memory types being mapped. MAIR_EL1.write( @@ -79,20 +80,21 @@ } /// Configure various settings of stage 1 of the EL1 translation regime. + #[inline(always)] fn configure_translation_control(&self) { - let t0sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; + let t1sz = (64 - bsp::memory::mmu::KernelVirtAddrSpace::SIZE_SHIFT) as u64; TCR_EL1.write( - TCR_EL1::TBI0::Used + TCR_EL1::TBI1::Used + TCR_EL1::IPS::Bits_40 - + TCR_EL1::TG0::KiB_64 - + TCR_EL1::SH0::Inner - + TCR_EL1::ORGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::IRGN0::WriteBack_ReadAlloc_WriteAlloc_Cacheable - + TCR_EL1::EPD0::EnableTTBR0Walks - + TCR_EL1::A1::TTBR0 - + TCR_EL1::T0SZ.val(t0sz) - + TCR_EL1::EPD1::DisableTTBR1Walks, + + TCR_EL1::TG1::KiB_64 + + TCR_EL1::SH1::Inner + + TCR_EL1::ORGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::IRGN1::WriteBack_ReadAlloc_WriteAlloc_Cacheable + + TCR_EL1::EPD1::EnableTTBR1Walks + + TCR_EL1::A1::TTBR1 + + TCR_EL1::T1SZ.val(t1sz) + + TCR_EL1::EPD0::DisableTTBR0Walks, ); } } @@ -131,7 +133,7 @@ self.set_up_mair(); // Set the "Translation Table Base Register". - TTBR0_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); + TTBR1_EL1.set_baddr(phys_tables_base_addr.as_usize() as u64); self.configure_translation_control(); diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld --- 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/kernel.ld +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld @@ -8,6 +8,13 @@ PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; +/* The kernel's virtual address range will be: + * + * [END_ADDRESS_INCLUSIVE, START_ADDRESS] + * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] + */ +__kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); + __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ @@ -26,34 +33,22 @@ */ PHDRS { - segment_boot_core_stack PT_LOAD FLAGS(6); segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); + segment_boot_core_stack PT_LOAD FLAGS(6); } SECTIONS { - . = __rpi_phys_dram_start_addr; - - /*********************************************************************************************** - * Boot Core Stack - ***********************************************************************************************/ - .boot_core_stack (NOLOAD) : - { - __boot_core_stack_start = .; /* ^ */ - /* | stack */ - . += __rpi_phys_binary_load_addr; /* | growth */ - /* | direction */ - __boot_core_stack_end_exclusive = .; /* | */ - } :segment_boot_core_stack + . = __kernel_virt_start_addr; - ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") + ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __code_start = .; - .text : + .text : AT(__rpi_phys_binary_load_addr) { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ @@ -91,6 +86,25 @@ . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; + ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") + + /*********************************************************************************************** + * Guard Page + ***********************************************************************************************/ + . += PAGE_SIZE; + + /*********************************************************************************************** + * Boot Core Stack + ***********************************************************************************************/ + .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) + { + __boot_core_stack_start = .; /* ^ */ + /* | stack */ + . += __rpi_phys_binary_load_addr; /* | growth */ + /* | direction */ + __boot_core_stack_end_exclusive = .; /* | */ + } :segment_boot_core_stack + ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory/mmu.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs @@ -20,7 +20,7 @@ //-------------------------------------------------------------------------------------------------- type KernelTranslationTable = - ::TableStartFromBottom; + ::TableStartFromTop; //-------------------------------------------------------------------------------------------------- // Public Definitions @@ -153,14 +153,6 @@ /// `translation table tool` and patched into the kernel binary. This function just adds the mapping /// record entries. pub fn kernel_add_mapping_records_for_precomputed() { - let virt_boot_core_stack_region = virt_boot_core_stack_region(); - generic_mmu::kernel_add_mapping_record( - "Kernel boot-core stack", - &virt_boot_core_stack_region, - &kernel_virt_to_phys_region(virt_boot_core_stack_region), - &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), - ); - let virt_code_region = virt_code_region(); generic_mmu::kernel_add_mapping_record( "Kernel code and RO data", @@ -176,4 +168,12 @@ &kernel_virt_to_phys_region(virt_data_region), &kernel_page_attributes(virt_data_region.start_page_addr()), ); + + let virt_boot_core_stack_region = virt_boot_core_stack_region(); + generic_mmu::kernel_add_mapping_record( + "Kernel boot-core stack", + &virt_boot_core_stack_region, + &kernel_virt_to_phys_region(virt_boot_core_stack_region), + &kernel_page_attributes(virt_boot_core_stack_region.start_page_addr()), + ); } diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/bsp/raspberrypi/memory.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs @@ -37,13 +37,7 @@ //! The virtual memory layout is as follows: //! //! +---------------------------------------+ -//! | | boot_core_stack_start @ 0x0 -//! | | ^ -//! | Boot-core Stack | | stack -//! | | | growth -//! | | | direction -//! +---------------------------------------+ -//! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive +//! | | code_start @ __kernel_virt_start_addr //! | .text | //! | .rodata | //! | .got | @@ -59,6 +53,16 @@ //! | | //! +---------------------------------------+ //! | | mmio_remap_end_exclusive +//! | Unmapped guard page | +//! | | +//! +---------------------------------------+ +//! | | boot_core_stack_start +//! | | ^ +//! | Boot-core Stack | | stack +//! | | | growth +//! | | | direction +//! +---------------------------------------+ +//! | | boot_core_stack_end_exclusive //! | | pub mod mmu; diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/lib.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs @@ -157,11 +157,6 @@ ) } -#[cfg(not(test))] -extern "Rust" { - fn kernel_init() -> !; -} - //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/translation_table.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs @@ -99,9 +99,9 @@ assert_eq!(tables.init(), Ok(())); - let virt_start_page_addr: PageAddress = PageAddress::from(0); - let virt_end_exclusive_page_addr: PageAddress = - virt_start_page_addr.checked_offset(5).unwrap(); + let virt_end_exclusive_page_addr: PageAddress = PageAddress::MAX; + let virt_start_page_addr: PageAddress = + virt_end_exclusive_page_addr.checked_offset(-5).unwrap(); let phys_start_page_addr: PageAddress = PageAddress::from(0); let phys_end_exclusive_page_addr: PageAddress = @@ -124,7 +124,7 @@ ); assert_eq!( - tables.try_page_attributes(virt_start_page_addr.checked_offset(6).unwrap()), + tables.try_page_attributes(virt_start_page_addr.checked_offset(-1).unwrap()), Err("Page marked invalid") ); diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu/types.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs @@ -67,6 +67,11 @@ // PageAddress //------------------------------------------------------------------------------ impl PageAddress { + /// The largest value that can be represented by this type. + pub const MAX: Self = PageAddress { + inner: Address::new(usize::MAX).align_down_page(), + }; + /// Unwraps the value. pub fn into_inner(self) -> Address { self.inner diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/src/memory/mmu.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs @@ -66,6 +66,11 @@ pub trait AssociatedTranslationTable { /// A translation table whose address range is: /// + /// [u64::MAX, (u64::MAX - AS_SIZE) + 1] + type TableStartFromTop; + + /// A translation table whose address range is: + /// /// [AS_SIZE - 1, 0] type TableStartFromBottom; } diff -uNr 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs 16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs --- 15_virtual_mem_part3_precomputed_tables/kernel/tests/02_exception_sync_page_fault.rs +++ 16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs @@ -28,8 +28,8 @@ // This line will be printed as the test header. println!("Testing synchronous exception handling by causing a page fault"); - info!("Writing beyond mapped area to address 9 GiB..."); - let big_addr: u64 = 9 * 1024 * 1024 * 1024; + info!("Writing to bottom of address space to address 1 GiB..."); + let big_addr: u64 = 1024 * 1024 * 1024; core::ptr::read_volatile(big_addr as *mut u64); // If execution reaches here, the memory access above did not cause a page fault exception. diff -uNr 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb --- 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/arch.rb +++ 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb @@ -255,6 +255,8 @@ end def lvl2_lvl3_index_from(addr) + addr -= BSP.kernel_virt_start_addr + lvl2_index = addr >> Granule512MiB::SHIFT lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT diff -uNr 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb --- 15_virtual_mem_part3_precomputed_tables/tools/translation_table_tool/bsp.rb +++ 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb @@ -6,7 +6,7 @@ # Raspberry Pi 3 + 4 class RaspberryPi - attr_reader :kernel_granule, :kernel_virt_addr_space_size + attr_reader :kernel_granule, :kernel_virt_addr_space_size, :kernel_virt_start_addr MEMORY_SRC = File.read('kernel/src/bsp/raspberrypi/memory.rs').split("\n") @@ -14,6 +14,7 @@ @kernel_granule = Granule64KiB @kernel_virt_addr_space_size = KERNEL_ELF.symbol_value('__kernel_virt_addr_space_size') + @kernel_virt_start_addr = KERNEL_ELF.symbol_value('__kernel_virt_start_addr') @virt_addr_of_kernel_tables = KERNEL_ELF.symbol_value('KERNEL_TABLES') @virt_addr_of_phys_kernel_tables_base_addr = KERNEL_ELF.symbol_value( ``` ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/build.rs ================================================ 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())); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // 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() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // 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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // 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::() ); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // 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) } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // 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)); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // 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); }); } } } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // 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()); } } }); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // 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 } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // 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()); } } }); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // 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(); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // 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(()) } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver/common.rs ================================================ // 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) } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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()); }; } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* SPDX-License-Identifier: MIT OR Apache-2.0 * * Copyright (c) 2018-2022 Andre Richter */ INCLUDE kernel_virt_addr_space_size.ld; PAGE_SIZE = 64K; PAGE_MASK = PAGE_SIZE - 1; /* The kernel's virtual address range will be: * * [END_ADDRESS_INCLUSIVE, START_ADDRESS] * [u64::MAX , (u64::MAX - __kernel_virt_addr_space_size) + 1] */ __kernel_virt_start_addr = ((0xffffffffffffffff - __kernel_virt_addr_space_size) + 1); __rpi_phys_dram_start_addr = 0; /* The physical address at which the the kernel binary will be loaded by the Raspberry's firmware */ __rpi_phys_binary_load_addr = 0x80000; ENTRY(__rpi_phys_binary_load_addr) /* Flags: * 4 == R * 5 == RX * 6 == RW * * Segments are marked PT_LOAD below so that the ELF file provides virtual and physical addresses. * It doesn't mean all of them need actually be loaded. */ PHDRS { segment_code PT_LOAD FLAGS(5); segment_data PT_LOAD FLAGS(6); segment_boot_core_stack PT_LOAD FLAGS(6); } SECTIONS { . = __kernel_virt_start_addr; ASSERT((. & PAGE_MASK) == 0, "Start of address space is not page aligned") /*********************************************************************************************** * Code + RO Data + Global Offset Table ***********************************************************************************************/ __code_start = .; .text : AT(__rpi_phys_binary_load_addr) { KEEP(*(.text._start)) *(.text._start_arguments) /* Constants (or statics in Rust speak) read by _start(). */ *(.text._start_rust) /* The Rust entry point */ *(.text*) /* Everything else */ } :segment_code .rodata : ALIGN(8) { *(.rodata*) } :segment_code . = ALIGN(PAGE_SIZE); __code_end_exclusive = .; /*********************************************************************************************** * Data + BSS ***********************************************************************************************/ __data_start = .; .data : { *(.data*) } :segment_data /* Section is zeroed in pairs of u64. Align start and end to 16 bytes */ .bss (NOLOAD) : ALIGN(16) { __bss_start = .; *(.bss*); . = ALIGN(16); __bss_end_exclusive = .; } :segment_data . = ALIGN(PAGE_SIZE); __data_end_exclusive = .; /*********************************************************************************************** * MMIO Remap Reserved ***********************************************************************************************/ __mmio_remap_start = .; . += 8 * 1024 * 1024; __mmio_remap_end_exclusive = .; ASSERT((. & PAGE_MASK) == 0, "MMIO remap reservation is not page aligned") /*********************************************************************************************** * Guard Page ***********************************************************************************************/ . += PAGE_SIZE; /*********************************************************************************************** * Boot Core Stack ***********************************************************************************************/ .boot_core_stack (NOLOAD) : AT(__rpi_phys_dram_start_addr) { __boot_core_stack_start = .; /* ^ */ /* | stack */ . += __rpi_phys_binary_load_addr; /* | growth */ /* | direction */ __boot_core_stack_end_exclusive = .; /* | */ } :segment_boot_core_stack ASSERT((. & PAGE_MASK) == 0, "End of boot core stack is not page aligned") /*********************************************************************************************** * Misc ***********************************************************************************************/ .got : { *(.got*) } ASSERT(SIZEOF(.got) == 0, "Relocation support not expected") /DISCARD/ : { *(.comment*) } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ================================================ __kernel_virt_addr_space_size = 1024 * 1024 * 1024 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // 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()), ); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //! //! The physical memory layout. //! //! The Raspberry's firmware copies the kernel binary to 0x8_0000. The preceding region will be used //! as the boot core's stack. //! //! +---------------------------------------+ //! | | boot_core_stack_start @ 0x0 //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | code_start @ 0x8_0000 == boot_core_stack_end_exclusive //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | data_start == code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | data_end_exclusive //! | | //! //! //! //! //! //! The virtual memory layout is as follows: //! //! +---------------------------------------+ //! | | code_start @ __kernel_virt_start_addr //! | .text | //! | .rodata | //! | .got | //! | | //! +---------------------------------------+ //! | | data_start == code_end_exclusive //! | .data | //! | .bss | //! | | //! +---------------------------------------+ //! | | mmio_remap_start == data_end_exclusive //! | VA region for MMIO remapping | //! | | //! +---------------------------------------+ //! | | mmio_remap_end_exclusive //! | Unmapped guard page | //! | | //! +---------------------------------------+ //! | | boot_core_stack_start //! | | ^ //! | Boot-core Stack | | stack //! | | | growth //! | | | direction //! +---------------------------------------+ //! | | boot_core_stack_end_exclusive //! | | pub mod mmu; use crate::memory::{mmu::PageAddress, Address, Physical, Virtual}; use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // Symbols from the linker script. extern "Rust" { static __code_start: UnsafeCell<()>; static __code_end_exclusive: UnsafeCell<()>; static __data_start: UnsafeCell<()>; static __data_end_exclusive: UnsafeCell<()>; static __mmio_remap_start: UnsafeCell<()>; static __mmio_remap_end_exclusive: UnsafeCell<()>; static __boot_core_stack_start: UnsafeCell<()>; static __boot_core_stack_end_exclusive: UnsafeCell<()>; } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { use super::*; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const PERIPHERAL_IC_START: Address = Address::new(0x3F00_B200); pub const PERIPHERAL_IC_SIZE: usize = 0x24; pub const GPIO_START: Address = Address::new(0x3F20_0000); pub const GPIO_SIZE: usize = 0xA0; pub const PL011_UART_START: Address = Address::new(0x3F20_1000); pub const PL011_UART_SIZE: usize = 0x48; pub const END: Address = Address::new(0x4001_0000); } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const GPIO_START: Address = Address::new(0xFE20_0000); pub const GPIO_SIZE: usize = 0xA0; pub const PL011_UART_START: Address = Address::new(0xFE20_1000); pub const PL011_UART_SIZE: usize = 0x48; pub const GICD_START: Address = Address::new(0xFF84_1000); pub const GICD_SIZE: usize = 0x824; pub const GICC_START: Address = Address::new(0xFF84_2000); pub const GICC_SIZE: usize = 0x14; pub const END: Address = Address::new(0xFF85_0000); } pub const END: Address = mmio::END; } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Start page address of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn virt_code_start() -> PageAddress { PageAddress::from(unsafe { __code_start.get() as usize }) } /// Size of the code segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn code_size() -> usize { unsafe { (__code_end_exclusive.get() as usize) - (__code_start.get() as usize) } } /// Start page address of the data segment. #[inline(always)] fn virt_data_start() -> PageAddress { PageAddress::from(unsafe { __data_start.get() as usize }) } /// Size of the data segment. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn data_size() -> usize { unsafe { (__data_end_exclusive.get() as usize) - (__data_start.get() as usize) } } /// Start page address of the MMIO remap reservation. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn virt_mmio_remap_start() -> PageAddress { PageAddress::from(unsafe { __mmio_remap_start.get() as usize }) } /// Size of the MMIO remap reservation. /// /// # Safety /// /// - Value is provided by the linker script and must be trusted as-is. #[inline(always)] fn mmio_remap_size() -> usize { unsafe { (__mmio_remap_end_exclusive.get() as usize) - (__mmio_remap_start.get() as usize) } } /// Start page address of the boot core's stack. #[inline(always)] fn virt_boot_core_stack_start() -> PageAddress { PageAddress::from(unsafe { __boot_core_stack_start.get() as usize }) } /// Size of the boot core's stack. #[inline(always)] fn boot_core_stack_size() -> usize { unsafe { (__boot_core_stack_end_exclusive.get() as usize) - (__boot_core_stack_start.get() as usize) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Exclusive end address of the physical address space. #[inline(always)] pub fn phys_addr_space_end_exclusive_addr() -> PageAddress { PageAddress::from(map::END) } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/lib.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` library. //! //! Used to compose the final kernel binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![allow(incomplete_features)] #![feature(asm_const)] #![feature(const_option)] #![feature(core_intrinsics)] #![feature(format_args_nl)] #![feature(generic_const_exprs)] #![feature(int_roundings)] #![feature(is_sorted)] #![feature(linkage)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(step_trait)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_std] // Testing #![cfg_attr(test, no_main)] #![feature(custom_test_frameworks)] #![reexport_test_harness_main = "test_main"] #![test_runner(crate::test_runner)] mod panic_wait; mod synchronization; pub mod bsp; pub mod common; pub mod console; pub mod cpu; pub mod driver; pub mod exception; pub mod memory; pub mod print; pub mod state; pub mod time; //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// Version string. pub fn version() -> &'static str { concat!( env!("CARGO_PKG_NAME"), " version ", env!("CARGO_PKG_VERSION") ) } //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- /// The default runner for unit tests. pub fn test_runner(tests: &[&test_types::UnitTest]) { // This line will be printed as the test header. println!("Running {} tests", tests.len()); for (i, test) in tests.iter().enumerate() { print!("{:>3}. {:.<58}", i + 1, test.name); // Run the actual test. (test.test_func)(); // Failed tests call panic!(). Execution reaches here only if the test has passed. println!("[ok]") } } /// The `kernel_init()` for unit tests. #[cfg(test)] #[no_mangle] unsafe fn kernel_init() -> ! { exception::handling_init(); memory::init(); bsp::driver::qemu_bring_up_console(); test_main(); cpu::qemu_exit_success() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/main.rs ================================================ // 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(); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/mapping_record.rs ================================================ // 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()); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/page_alloc.rs ================================================ // 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) } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/translation_table.rs ================================================ // 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)); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu/types.rs ================================================ // 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 ); } } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory/mmu.rs ================================================ // 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) } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/memory.rs ================================================ // 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); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/00_console_sanity.rs ================================================ // 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(); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/01_timer_sanity.rs ================================================ // 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) } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/02_exception_sync_page_fault.rs ================================================ // 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() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/03_exception_restore_sanity.rs ================================================ // 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(); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/04_exception_irq_sanity.rs ================================================ // 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()); } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/arch.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField def initialize @value = 0 end def self.attr_bitfield(name, offset, num_bits) define_method("#{name}=") do |bits| mask = (2**num_bits) - 1 raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? # Clear bitfield @value &= ~(mask << offset) # Set it @value |= (bits << offset) end end def to_i @value end def size_in_byte 8 end end # An array class that knows its memory location. class CArray < Array attr_reader :phys_start_addr def initialize(phys_start_addr, size, &block) @phys_start_addr = phys_start_addr super(size, &block) end def size_in_byte inject(0) { |sum, n| sum + n.size_in_byte } end end #--------------------------------------------------------------------------------------------------- # Arch:: #--------------------------------------------------------------------------------------------------- module Arch #--------------------------------------------------------------------------------------------------- # Arch::ARMv8 #--------------------------------------------------------------------------------------------------- module ARMv8 # ARMv8 Table Descriptor. class Stage1TableDescriptor < BitField module NextLevelTableAddr OFFSET = 16 NUMBITS = 32 end module Type OFFSET = 1 NUMBITS = 1 BLOCK = 0 TABLE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def next_level_table_addr=(addr) addr >>= Granule64KiB::SHIFT self.__next_level_table_addr = addr end private :__next_level_table_addr= end # ARMv8 level 3 page descriptor. class Stage1PageDescriptor < BitField module UXN OFFSET = 54 NUMBITS = 1 FALSE = 0 TRUE = 1 end module PXN OFFSET = 53 NUMBITS = 1 FALSE = 0 TRUE = 1 end module OutputAddr OFFSET = 16 NUMBITS = 32 end module AF OFFSET = 10 NUMBITS = 1 FALSE = 0 TRUE = 1 end module SH OFFSET = 8 NUMBITS = 2 INNER_SHAREABLE = 0b11 end module AP OFFSET = 6 NUMBITS = 2 RW_EL1 = 0b00 RO_EL1 = 0b10 end module AttrIndx OFFSET = 2 NUMBITS = 3 end module Type OFFSET = 1 NUMBITS = 1 RESERVED_INVALID = 0 PAGE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def output_addr=(addr) addr >>= Granule64KiB::SHIFT self.__output_addr = addr end private :__output_addr= end # Translation table representing the structure defined in translation_table.rs. class TranslationTable module MAIR NORMAL = 1 end def initialize do_sanity_checks num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) populate_lvl2_entries end def map_at(virt_region, phys_region, attributes) return if virt_region.empty? raise if virt_region.size != phys_region.size raise if phys_region.last > BSP.phys_addr_space_end_page virt_region.zip(phys_region).each do |virt_page, phys_page| desc = page_descriptor_from(virt_page) set_lvl3_entry(desc, phys_page, attributes) end end def to_binary data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) data.pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr_binary [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr @lvl2_phys_start_addr end private def do_sanity_checks raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? end def new_lvl3(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do temp = CArray.new(start_addr, 8192) do Stage1PageDescriptor.new end start_addr += temp.size_in_byte temp end end def new_lvl2(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do Stage1TableDescriptor.new end end def populate_lvl2_entries @lvl2.each_with_index do |descriptor, i| descriptor.next_level_table_addr = @lvl3[i].phys_start_addr descriptor.type = Stage1TableDescriptor::Type::TABLE descriptor.valid = Stage1TableDescriptor::Valid::TRUE end end def lvl2_lvl3_index_from(addr) addr -= BSP.kernel_virt_start_addr lvl2_index = addr >> Granule512MiB::SHIFT lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT raise unless lvl2_index < @lvl2.size [lvl2_index, lvl3_index] end def page_descriptor_from(virt_addr) lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) @lvl3[lvl2_index][lvl3_index] end # rubocop:disable Metrics/MethodLength def set_attributes(desc, attributes) case attributes.mem_attributes when :CacheableDRAM desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE desc.attr_indx = MAIR::NORMAL else raise 'Invalid input' end desc.ap = case attributes.acc_perms when :ReadOnly Stage1PageDescriptor::AP::RO_EL1 when :ReadWrite Stage1PageDescriptor::AP::RW_EL1 else raise 'Invalid input' end desc.pxn = if attributes.execute_never Stage1PageDescriptor::PXN::TRUE else Stage1PageDescriptor::PXN::FALSE end desc.uxn = Stage1PageDescriptor::UXN::TRUE end # rubocop:enable Metrics/MethodLength def set_lvl3_entry(desc, output_addr, attributes) desc.output_addr = output_addr desc.af = Stage1PageDescriptor::AF::TRUE desc.type = Stage1PageDescriptor::Type::PAGE desc.valid = Stage1PageDescriptor::Valid::TRUE set_attributes(desc, attributes) end end end end ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/bsp.rb ================================================ # 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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/generic.rb ================================================ # 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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 16_virtual_mem_part4_higher_half_kernel/tools/translation_table_tool/main.rb ================================================ #!/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" ================================================ FILE: 17_kernel_symbols/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 17_kernel_symbols/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 17_kernel_symbols/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel", "kernel_symbols" ] [profile.release] lto = true ================================================ FILE: 17_kernel_symbols/Makefile ================================================ ## 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 ================================================ FILE: 17_kernel_symbols/README.md ================================================ # 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 ``` ================================================ FILE: 17_kernel_symbols/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 17_kernel_symbols/kernel/build.rs ================================================ 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())); } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // 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 ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // 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::() ); } } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // 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) } } ================================================ FILE: 17_kernel_symbols/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // 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)); } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // 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); }); } } } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // 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()); } } }); } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // 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 } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // 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()); } } }); } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // 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(); } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // 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(()) } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver/common.rs ================================================ // 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) } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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()); }; } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ================================================ __kernel_virt_addr_space_size = 1024 * 1024 * 1024 ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // 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()), ); } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi/memory.rs ================================================ // 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) } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 17_kernel_symbols/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 17_kernel_symbols/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 17_kernel_symbols/kernel/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 17_kernel_symbols/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 17_kernel_symbols/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 17_kernel_symbols/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 17_kernel_symbols/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 17_kernel_symbols/kernel/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 17_kernel_symbols/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 17_kernel_symbols/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 17_kernel_symbols/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 17_kernel_symbols/kernel/src/lib.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/kernel/src/main.rs ================================================ // 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(); } ================================================ FILE: 17_kernel_symbols/kernel/src/memory/mmu/mapping_record.rs ================================================ // 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()); } ================================================ FILE: 17_kernel_symbols/kernel/src/memory/mmu/page_alloc.rs ================================================ // 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) } } ================================================ FILE: 17_kernel_symbols/kernel/src/memory/mmu/translation_table.rs ================================================ // 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)); } } ================================================ FILE: 17_kernel_symbols/kernel/src/memory/mmu/types.rs ================================================ // 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 ); } } } ================================================ FILE: 17_kernel_symbols/kernel/src/memory/mmu.rs ================================================ // 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) } ================================================ FILE: 17_kernel_symbols/kernel/src/memory.rs ================================================ // 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); } } ================================================ FILE: 17_kernel_symbols/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/kernel/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 17_kernel_symbols/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 17_kernel_symbols/kernel/src/symbols.rs ================================================ // 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"); } } ================================================ FILE: 17_kernel_symbols/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 17_kernel_symbols/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 17_kernel_symbols/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 17_kernel_symbols/kernel/tests/00_console_sanity.rs ================================================ // 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(); } ================================================ FILE: 17_kernel_symbols/kernel/tests/01_timer_sanity.rs ================================================ // 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) } ================================================ FILE: 17_kernel_symbols/kernel/tests/02_exception_sync_page_fault.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 17_kernel_symbols/kernel/tests/03_exception_restore_sanity.rs ================================================ // 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(); } ================================================ FILE: 17_kernel_symbols/kernel/tests/04_exception_irq_sanity.rs ================================================ // 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()); } ================================================ FILE: 17_kernel_symbols/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 17_kernel_symbols/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/kernel_symbols/Cargo.toml ================================================ [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" } ================================================ FILE: 17_kernel_symbols/kernel_symbols/build.rs ================================================ 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() ); } ================================================ FILE: 17_kernel_symbols/kernel_symbols/kernel_symbols.ld ================================================ /* 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*) } } ================================================ FILE: 17_kernel_symbols/kernel_symbols/src/main.rs ================================================ // 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!() } ================================================ FILE: 17_kernel_symbols/kernel_symbols.mk ================================================ ## 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 ================================================ FILE: 17_kernel_symbols/libraries/debug-symbol-types/Cargo.toml ================================================ [package] name = "debug-symbol-types" version = "0.1.0" edition = "2021" ================================================ FILE: 17_kernel_symbols/libraries/debug-symbol-types/src/lib.rs ================================================ // 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 } } ================================================ FILE: 17_kernel_symbols/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 17_kernel_symbols/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 17_kernel_symbols/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 17_kernel_symbols/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 17_kernel_symbols/tools/kernel_symbols_tool/cmds.rb ================================================ # 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 ================================================ FILE: 17_kernel_symbols/tools/kernel_symbols_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 17_kernel_symbols/tools/kernel_symbols_tool/main.rb ================================================ #!/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 ================================================ FILE: 17_kernel_symbols/tools/translation_table_tool/arch.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField def initialize @value = 0 end def self.attr_bitfield(name, offset, num_bits) define_method("#{name}=") do |bits| mask = (2**num_bits) - 1 raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? # Clear bitfield @value &= ~(mask << offset) # Set it @value |= (bits << offset) end end def to_i @value end def size_in_byte 8 end end # An array class that knows its memory location. class CArray < Array attr_reader :phys_start_addr def initialize(phys_start_addr, size, &block) @phys_start_addr = phys_start_addr super(size, &block) end def size_in_byte inject(0) { |sum, n| sum + n.size_in_byte } end end #--------------------------------------------------------------------------------------------------- # Arch:: #--------------------------------------------------------------------------------------------------- module Arch #--------------------------------------------------------------------------------------------------- # Arch::ARMv8 #--------------------------------------------------------------------------------------------------- module ARMv8 # ARMv8 Table Descriptor. class Stage1TableDescriptor < BitField module NextLevelTableAddr OFFSET = 16 NUMBITS = 32 end module Type OFFSET = 1 NUMBITS = 1 BLOCK = 0 TABLE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def next_level_table_addr=(addr) addr >>= Granule64KiB::SHIFT self.__next_level_table_addr = addr end private :__next_level_table_addr= end # ARMv8 level 3 page descriptor. class Stage1PageDescriptor < BitField module UXN OFFSET = 54 NUMBITS = 1 FALSE = 0 TRUE = 1 end module PXN OFFSET = 53 NUMBITS = 1 FALSE = 0 TRUE = 1 end module OutputAddr OFFSET = 16 NUMBITS = 32 end module AF OFFSET = 10 NUMBITS = 1 FALSE = 0 TRUE = 1 end module SH OFFSET = 8 NUMBITS = 2 INNER_SHAREABLE = 0b11 end module AP OFFSET = 6 NUMBITS = 2 RW_EL1 = 0b00 RO_EL1 = 0b10 end module AttrIndx OFFSET = 2 NUMBITS = 3 end module Type OFFSET = 1 NUMBITS = 1 RESERVED_INVALID = 0 PAGE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def output_addr=(addr) addr >>= Granule64KiB::SHIFT self.__output_addr = addr end private :__output_addr= end # Translation table representing the structure defined in translation_table.rs. class TranslationTable module MAIR NORMAL = 1 end def initialize do_sanity_checks num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) populate_lvl2_entries end def map_at(virt_region, phys_region, attributes) return if virt_region.empty? raise if virt_region.size != phys_region.size raise if phys_region.last > BSP.phys_addr_space_end_page virt_region.zip(phys_region).each do |virt_page, phys_page| desc = page_descriptor_from(virt_page) set_lvl3_entry(desc, phys_page, attributes) end end def to_binary data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) data.pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr_binary [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr @lvl2_phys_start_addr end private def do_sanity_checks raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? end def new_lvl3(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do temp = CArray.new(start_addr, 8192) do Stage1PageDescriptor.new end start_addr += temp.size_in_byte temp end end def new_lvl2(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do Stage1TableDescriptor.new end end def populate_lvl2_entries @lvl2.each_with_index do |descriptor, i| descriptor.next_level_table_addr = @lvl3[i].phys_start_addr descriptor.type = Stage1TableDescriptor::Type::TABLE descriptor.valid = Stage1TableDescriptor::Valid::TRUE end end def lvl2_lvl3_index_from(addr) addr -= BSP.kernel_virt_start_addr lvl2_index = addr >> Granule512MiB::SHIFT lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT raise unless lvl2_index < @lvl2.size [lvl2_index, lvl3_index] end def page_descriptor_from(virt_addr) lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) @lvl3[lvl2_index][lvl3_index] end # rubocop:disable Metrics/MethodLength def set_attributes(desc, attributes) case attributes.mem_attributes when :CacheableDRAM desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE desc.attr_indx = MAIR::NORMAL else raise 'Invalid input' end desc.ap = case attributes.acc_perms when :ReadOnly Stage1PageDescriptor::AP::RO_EL1 when :ReadWrite Stage1PageDescriptor::AP::RW_EL1 else raise 'Invalid input' end desc.pxn = if attributes.execute_never Stage1PageDescriptor::PXN::TRUE else Stage1PageDescriptor::PXN::FALSE end desc.uxn = Stage1PageDescriptor::UXN::TRUE end # rubocop:enable Metrics/MethodLength def set_lvl3_entry(desc, output_addr, attributes) desc.output_addr = output_addr desc.af = Stage1PageDescriptor::AF::TRUE desc.type = Stage1PageDescriptor::Type::PAGE desc.valid = Stage1PageDescriptor::Valid::TRUE set_attributes(desc, attributes) end end end end ================================================ FILE: 17_kernel_symbols/tools/translation_table_tool/bsp.rb ================================================ # 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 ================================================ FILE: 17_kernel_symbols/tools/translation_table_tool/generic.rb ================================================ # 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 ================================================ FILE: 17_kernel_symbols/tools/translation_table_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 17_kernel_symbols/tools/translation_table_tool/main.rb ================================================ #!/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" ================================================ FILE: 18_backtrace/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 18_backtrace/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 18_backtrace/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel", "kernel_symbols" ] [profile.release] lto = true debug = true ================================================ FILE: 18_backtrace/Makefile ================================================ ## 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 ================================================ FILE: 18_backtrace/README.md ================================================ # 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 ``` ================================================ FILE: 18_backtrace/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 18_backtrace/kernel/build.rs ================================================ 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())); } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/backtrace.rs ================================================ // 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); } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // 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 ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // 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::() ); } } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // 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) } } ================================================ FILE: 18_backtrace/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 18_backtrace/kernel/src/backtrace.rs ================================================ // 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, " ----------------------------------------------------------------------------------------------" ) } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // 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)); } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // 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); }); } } } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // 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()); } } }); } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // 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 } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // 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()); } } }); } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // 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(); } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // 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(()) } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver/common.rs ================================================ // 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) } } ================================================ FILE: 18_backtrace/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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()); }; } ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ================================================ __kernel_virt_addr_space_size = 1024 * 1024 * 1024 ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // 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()), ); } ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi/memory.rs ================================================ // 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) } ================================================ FILE: 18_backtrace/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 18_backtrace/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 18_backtrace/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 18_backtrace/kernel/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: 18_backtrace/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 18_backtrace/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 18_backtrace/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 18_backtrace/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 18_backtrace/kernel/src/driver.rs ================================================ // 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; }); } } ================================================ FILE: 18_backtrace/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 18_backtrace/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 18_backtrace/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 18_backtrace/kernel/src/lib.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/src/main.rs ================================================ // 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(); } ================================================ FILE: 18_backtrace/kernel/src/memory/mmu/mapping_record.rs ================================================ // 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()); } ================================================ FILE: 18_backtrace/kernel/src/memory/mmu/page_alloc.rs ================================================ // 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) } } ================================================ FILE: 18_backtrace/kernel/src/memory/mmu/translation_table.rs ================================================ // 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)); } } ================================================ FILE: 18_backtrace/kernel/src/memory/mmu/types.rs ================================================ // 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 ); } } } ================================================ FILE: 18_backtrace/kernel/src/memory/mmu.rs ================================================ // 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) } ================================================ FILE: 18_backtrace/kernel/src/memory.rs ================================================ // 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); } } ================================================ FILE: 18_backtrace/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: 18_backtrace/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 18_backtrace/kernel/src/symbols.rs ================================================ // 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"); } } ================================================ FILE: 18_backtrace/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 18_backtrace/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 18_backtrace/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 18_backtrace/kernel/tests/00_console_sanity.rs ================================================ // 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(); } ================================================ FILE: 18_backtrace/kernel/tests/01_timer_sanity.rs ================================================ // 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) } ================================================ FILE: 18_backtrace/kernel/tests/02_exception_sync_page_fault.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 18_backtrace/kernel/tests/03_exception_restore_sanity.rs ================================================ // 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(); } ================================================ FILE: 18_backtrace/kernel/tests/04_exception_irq_sanity.rs ================================================ // 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()); } ================================================ FILE: 18_backtrace/kernel/tests/05_backtrace_sanity.rb ================================================ # 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 ================================================ FILE: 18_backtrace/kernel/tests/05_backtrace_sanity.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/tests/06_backtrace_invalid_frame.rb ================================================ # 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 ================================================ FILE: 18_backtrace/kernel/tests/06_backtrace_invalid_frame.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/tests/07_backtrace_invalid_link.rb ================================================ # 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 ================================================ FILE: 18_backtrace/kernel/tests/07_backtrace_invalid_link.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 18_backtrace/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/kernel_symbols/Cargo.toml ================================================ [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" } ================================================ FILE: 18_backtrace/kernel_symbols/build.rs ================================================ 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() ); } ================================================ FILE: 18_backtrace/kernel_symbols/kernel_symbols.ld ================================================ /* 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*) } } ================================================ FILE: 18_backtrace/kernel_symbols/src/main.rs ================================================ // 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!() } ================================================ FILE: 18_backtrace/kernel_symbols.mk ================================================ ## 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 ================================================ FILE: 18_backtrace/libraries/debug-symbol-types/Cargo.toml ================================================ [package] name = "debug-symbol-types" version = "0.1.0" edition = "2021" ================================================ FILE: 18_backtrace/libraries/debug-symbol-types/src/lib.rs ================================================ // 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 } } ================================================ FILE: 18_backtrace/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 18_backtrace/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 18_backtrace/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 18_backtrace/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 18_backtrace/tools/kernel_symbols_tool/cmds.rb ================================================ # 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 ================================================ FILE: 18_backtrace/tools/kernel_symbols_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 18_backtrace/tools/kernel_symbols_tool/main.rb ================================================ #!/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 ================================================ FILE: 18_backtrace/tools/translation_table_tool/arch.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField def initialize @value = 0 end def self.attr_bitfield(name, offset, num_bits) define_method("#{name}=") do |bits| mask = (2**num_bits) - 1 raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? # Clear bitfield @value &= ~(mask << offset) # Set it @value |= (bits << offset) end end def to_i @value end def size_in_byte 8 end end # An array class that knows its memory location. class CArray < Array attr_reader :phys_start_addr def initialize(phys_start_addr, size, &block) @phys_start_addr = phys_start_addr super(size, &block) end def size_in_byte inject(0) { |sum, n| sum + n.size_in_byte } end end #--------------------------------------------------------------------------------------------------- # Arch:: #--------------------------------------------------------------------------------------------------- module Arch #--------------------------------------------------------------------------------------------------- # Arch::ARMv8 #--------------------------------------------------------------------------------------------------- module ARMv8 # ARMv8 Table Descriptor. class Stage1TableDescriptor < BitField module NextLevelTableAddr OFFSET = 16 NUMBITS = 32 end module Type OFFSET = 1 NUMBITS = 1 BLOCK = 0 TABLE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def next_level_table_addr=(addr) addr >>= Granule64KiB::SHIFT self.__next_level_table_addr = addr end private :__next_level_table_addr= end # ARMv8 level 3 page descriptor. class Stage1PageDescriptor < BitField module UXN OFFSET = 54 NUMBITS = 1 FALSE = 0 TRUE = 1 end module PXN OFFSET = 53 NUMBITS = 1 FALSE = 0 TRUE = 1 end module OutputAddr OFFSET = 16 NUMBITS = 32 end module AF OFFSET = 10 NUMBITS = 1 FALSE = 0 TRUE = 1 end module SH OFFSET = 8 NUMBITS = 2 INNER_SHAREABLE = 0b11 end module AP OFFSET = 6 NUMBITS = 2 RW_EL1 = 0b00 RO_EL1 = 0b10 end module AttrIndx OFFSET = 2 NUMBITS = 3 end module Type OFFSET = 1 NUMBITS = 1 RESERVED_INVALID = 0 PAGE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def output_addr=(addr) addr >>= Granule64KiB::SHIFT self.__output_addr = addr end private :__output_addr= end # Translation table representing the structure defined in translation_table.rs. class TranslationTable module MAIR NORMAL = 1 end def initialize do_sanity_checks num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) populate_lvl2_entries end def map_at(virt_region, phys_region, attributes) return if virt_region.empty? raise if virt_region.size != phys_region.size raise if phys_region.last > BSP.phys_addr_space_end_page virt_region.zip(phys_region).each do |virt_page, phys_page| desc = page_descriptor_from(virt_page) set_lvl3_entry(desc, phys_page, attributes) end end def to_binary data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) data.pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr_binary [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr @lvl2_phys_start_addr end private def do_sanity_checks raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? end def new_lvl3(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do temp = CArray.new(start_addr, 8192) do Stage1PageDescriptor.new end start_addr += temp.size_in_byte temp end end def new_lvl2(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do Stage1TableDescriptor.new end end def populate_lvl2_entries @lvl2.each_with_index do |descriptor, i| descriptor.next_level_table_addr = @lvl3[i].phys_start_addr descriptor.type = Stage1TableDescriptor::Type::TABLE descriptor.valid = Stage1TableDescriptor::Valid::TRUE end end def lvl2_lvl3_index_from(addr) addr -= BSP.kernel_virt_start_addr lvl2_index = addr >> Granule512MiB::SHIFT lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT raise unless lvl2_index < @lvl2.size [lvl2_index, lvl3_index] end def page_descriptor_from(virt_addr) lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) @lvl3[lvl2_index][lvl3_index] end # rubocop:disable Metrics/MethodLength def set_attributes(desc, attributes) case attributes.mem_attributes when :CacheableDRAM desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE desc.attr_indx = MAIR::NORMAL else raise 'Invalid input' end desc.ap = case attributes.acc_perms when :ReadOnly Stage1PageDescriptor::AP::RO_EL1 when :ReadWrite Stage1PageDescriptor::AP::RW_EL1 else raise 'Invalid input' end desc.pxn = if attributes.execute_never Stage1PageDescriptor::PXN::TRUE else Stage1PageDescriptor::PXN::FALSE end desc.uxn = Stage1PageDescriptor::UXN::TRUE end # rubocop:enable Metrics/MethodLength def set_lvl3_entry(desc, output_addr, attributes) desc.output_addr = output_addr desc.af = Stage1PageDescriptor::AF::TRUE desc.type = Stage1PageDescriptor::Type::PAGE desc.valid = Stage1PageDescriptor::Valid::TRUE set_attributes(desc, attributes) end end end end ================================================ FILE: 18_backtrace/tools/translation_table_tool/bsp.rb ================================================ # 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 ================================================ FILE: 18_backtrace/tools/translation_table_tool/generic.rb ================================================ # 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 ================================================ FILE: 18_backtrace/tools/translation_table_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 18_backtrace/tools/translation_table_tool/main.rb ================================================ #!/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" ================================================ FILE: 19_kernel_heap/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 19_kernel_heap/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 19_kernel_heap/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel", "kernel_symbols" ] [profile.release] lto = true debug = true ================================================ FILE: 19_kernel_heap/Makefile ================================================ ## 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 ================================================ FILE: 19_kernel_heap/README.md ================================================ # 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 ``` ================================================ FILE: 19_kernel_heap/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 19_kernel_heap/kernel/build.rs ================================================ 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())); } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/backtrace.rs ================================================ // 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); } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // 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 ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // 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::() ); } } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // 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) } } ================================================ FILE: 19_kernel_heap/kernel/src/_arch/aarch64/time.rs ================================================ // 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 {} } ================================================ FILE: 19_kernel_heap/kernel/src/backtrace.rs ================================================ // 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, " ----------------------------------------------------------------------------------------------" ) } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // 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)); } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // 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); }); } } } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // 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()); } } }); } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // 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 } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Peripheral Interrupt Controller Driver. //! //! # Resources //! //! - use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, exception, memory::{Address, Virtual}, synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; use alloc::vec::Vec; use tock_registers::{ interfaces::{Readable, Writeable}, register_structs, registers::{ReadOnly, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- register_structs! { #[allow(non_snake_case)] WORegisterBlock { (0x00 => _reserved1), (0x10 => ENABLE_1: WriteOnly), (0x14 => ENABLE_2: WriteOnly), (0x18 => @END), } } register_structs! { #[allow(non_snake_case)] RORegisterBlock { (0x00 => _reserved1), (0x04 => PENDING_1: ReadOnly), (0x08 => PENDING_2: ReadOnly), (0x0c => @END), } } /// Abstraction for the WriteOnly parts of the associated MMIO registers. type WriteOnlyRegisters = MMIODerefWrapper; /// Abstraction for the ReadOnly parts of the associated MMIO registers. type ReadOnlyRegisters = MMIODerefWrapper; type HandlerTable = Vec>>; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the peripheral interrupt controller. pub struct PeripheralIC { /// Access to write registers is guarded with a lock. wo_registers: IRQSafeNullLock, /// Register read access is unguarded. ro_registers: ReadOnlyRegisters, /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. handler_table: InitStateLock, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PeripheralIC { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), ro_registers: ReadOnlyRegisters::new(mmio_start_addr), handler_table: InitStateLock::new(Vec::new()), } } /// Called by the kernel to bring up the device. pub fn init(&self) { self.handler_table .write(|table| table.resize(PeripheralIRQ::MAX_INCLUSIVE + 1, None)); } /// Query the list of pending IRQs. fn pending_irqs(&self) -> PendingIRQs { let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) | u64::from(self.ro_registers.PENDING_1.get()); PendingIRQs::new(pending_mask) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::{Mutex, ReadWriteEx}; impl exception::asynchronous::interface::IRQManager for PeripheralIC { type IRQNumberType = PeripheralIRQ; fn register_handler( &self, irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } fn enable(&self, irq: &Self::IRQNumberType) { self.wo_registers.lock(|regs| { let enable_reg = if irq.get() <= 31 { ®s.ENABLE_1 } else { ®s.ENABLE_2 }; let enable_bit: u32 = 1 << (irq.get() % 32); // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable // bits are unaffected. So we don't need read and OR'ing here. enable_reg.set(enable_bit); }); } fn handle_pending_irqs<'irq_context>( &'irq_context self, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) { self.handler_table.read(|table| { for irq_number in self.pending_irqs() { match table[irq_number] { None => panic!("No handler registered for IRQ {}", irq_number), Some(descriptor) => { // Call the IRQ handler. Panics on failure. descriptor.handler().handle().expect("Error handling IRQ"); } } } }) } fn print_handler(&self) { use crate::info; info!(" Peripheral handler:"); self.handler_table.read(|table| { for (i, opt) in table.iter().enumerate() { if let Some(handler) = opt { info!(" {: >3}. {}", i, handler.name()); } } }); } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // 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(); } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception::{self, asynchronous::IRQNumber}, memory::{Address, Virtual}, synchronization, synchronization::IRQSafeNullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt FIFO Level Select Register. IFLS [ /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as /// follows. RXIFLSEL OFFSET(3) NUMBITS(5) [ OneEigth = 0b000, OneQuarter = 0b001, OneHalf = 0b010, ThreeQuarters = 0b011, SevenEights = 0b100 ] ], /// Interrupt Mask Set/Clear Register. IMSC [ /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR /// interrupt. /// /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. /// - A write of 0 clears the mask. RTIM OFFSET(6) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. /// /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. /// - A write of 0 clears the mask. RXIM OFFSET(4) NUMBITS(1) [ Disabled = 0, Enabled = 1 ] ], /// Masked Interrupt Status Register. MIS [ /// Receive timeout masked interrupt status. Returns the masked interrupt state of the /// UARTRTINTR interrupt. RTMIS OFFSET(6) NUMBITS(1) [], /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR /// interrupt. RXMIS OFFSET(4) NUMBITS(1) [] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => IFLS: ReadWrite), (0x38 => IMSC: ReadWrite), (0x3C => _reserved3), (0x40 => MIS: ReadOnly), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Set RX FIFO fill level at 1/8. self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); // Enable RX IRQ + RX timeout IRQ. self.registers .IMSC .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Send a slice of characters. fn write_array(&mut self, a: &[char]) { for c in a { self.write_char(*c); } } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { type IRQNumberType = IRQNumber; fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } fn register_and_enable_irq_handler( &'static self, irq_number: &Self::IRQNumberType, ) -> Result<(), &'static str> { use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); irq_manager().register_handler(descriptor)?; irq_manager().enable(irq_number); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_array(&self, a: &[char]) { self.inner.lock(|inner| inner.write_array(a)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { let pending = inner.registers.MIS.extract(); // Clear all pending IRQs. inner.registers.ICR.write(ICR::ALL::CLEAR); // Check for any kind of RX interrupt. if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { // Echo any received characters. while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { inner.write_char(c) } } }); Ok(()) } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver/common.rs ================================================ // 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) } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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()); }; } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ================================================ __kernel_virt_addr_space_size = 1024 * 1024 * 1024 ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // 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()), ); } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi/memory.rs ================================================ // 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) } ================================================ FILE: 19_kernel_heap/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 19_kernel_heap/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 19_kernel_heap/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 19_kernel_heap/kernel/src/console/buffer_console.rs ================================================ // 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 {} ================================================ FILE: 19_kernel_heap/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 19_kernel_heap/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 19_kernel_heap/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 19_kernel_heap/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 19_kernel_heap/kernel/src/driver.rs ================================================ // 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()); } }); } } ================================================ FILE: 19_kernel_heap/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 19_kernel_heap/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 19_kernel_heap/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 19_kernel_heap/kernel/src/lib.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/src/main.rs ================================================ // 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(); } ================================================ FILE: 19_kernel_heap/kernel/src/memory/heap_alloc.rs ================================================ // 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); } ================================================ FILE: 19_kernel_heap/kernel/src/memory/mmu/mapping_record.rs ================================================ // 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()); } ================================================ FILE: 19_kernel_heap/kernel/src/memory/mmu/page_alloc.rs ================================================ // 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) } } ================================================ FILE: 19_kernel_heap/kernel/src/memory/mmu/translation_table.rs ================================================ // 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)); } } ================================================ FILE: 19_kernel_heap/kernel/src/memory/mmu/types.rs ================================================ // 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 ); } } } ================================================ FILE: 19_kernel_heap/kernel/src/memory/mmu.rs ================================================ // 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) } ================================================ FILE: 19_kernel_heap/kernel/src/memory.rs ================================================ // 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); } } ================================================ FILE: 19_kernel_heap/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/src/print.rs ================================================ // 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)* )); } }) } ================================================ FILE: 19_kernel_heap/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 19_kernel_heap/kernel/src/symbols.rs ================================================ // 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"); } } ================================================ FILE: 19_kernel_heap/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 19_kernel_heap/kernel/src/time.rs ================================================ // 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) } } ================================================ FILE: 19_kernel_heap/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/kernel/tests/00_console_sanity.rs ================================================ // 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(); } ================================================ FILE: 19_kernel_heap/kernel/tests/01_timer_sanity.rs ================================================ // 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) } ================================================ FILE: 19_kernel_heap/kernel/tests/02_exception_sync_page_fault.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/kernel/tests/03_exception_restore_sanity.rs ================================================ // 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(); } ================================================ FILE: 19_kernel_heap/kernel/tests/04_exception_irq_sanity.rs ================================================ // 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()); } ================================================ FILE: 19_kernel_heap/kernel/tests/05_backtrace_sanity.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/kernel/tests/05_backtrace_sanity.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/kernel/tests/06_backtrace_invalid_frame.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/kernel/tests/07_backtrace_invalid_link.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Echoing input now' ================================================ FILE: 19_kernel_heap/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/kernel_symbols/Cargo.toml ================================================ [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" } ================================================ FILE: 19_kernel_heap/kernel_symbols/build.rs ================================================ 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() ); } ================================================ FILE: 19_kernel_heap/kernel_symbols/kernel_symbols.ld ================================================ /* 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*) } } ================================================ FILE: 19_kernel_heap/kernel_symbols/src/main.rs ================================================ // 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!() } ================================================ FILE: 19_kernel_heap/kernel_symbols.mk ================================================ ## 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 ================================================ FILE: 19_kernel_heap/libraries/debug-symbol-types/Cargo.toml ================================================ [package] name = "debug-symbol-types" version = "0.1.0" edition = "2021" ================================================ FILE: 19_kernel_heap/libraries/debug-symbol-types/src/lib.rs ================================================ // 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 } } ================================================ FILE: 19_kernel_heap/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 19_kernel_heap/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 19_kernel_heap/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 19_kernel_heap/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 19_kernel_heap/tools/kernel_symbols_tool/cmds.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/tools/kernel_symbols_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/tools/kernel_symbols_tool/main.rb ================================================ #!/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 ================================================ FILE: 19_kernel_heap/tools/translation_table_tool/arch.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField def initialize @value = 0 end def self.attr_bitfield(name, offset, num_bits) define_method("#{name}=") do |bits| mask = (2**num_bits) - 1 raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? # Clear bitfield @value &= ~(mask << offset) # Set it @value |= (bits << offset) end end def to_i @value end def size_in_byte 8 end end # An array class that knows its memory location. class CArray < Array attr_reader :phys_start_addr def initialize(phys_start_addr, size, &block) @phys_start_addr = phys_start_addr super(size, &block) end def size_in_byte inject(0) { |sum, n| sum + n.size_in_byte } end end #--------------------------------------------------------------------------------------------------- # Arch:: #--------------------------------------------------------------------------------------------------- module Arch #--------------------------------------------------------------------------------------------------- # Arch::ARMv8 #--------------------------------------------------------------------------------------------------- module ARMv8 # ARMv8 Table Descriptor. class Stage1TableDescriptor < BitField module NextLevelTableAddr OFFSET = 16 NUMBITS = 32 end module Type OFFSET = 1 NUMBITS = 1 BLOCK = 0 TABLE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def next_level_table_addr=(addr) addr >>= Granule64KiB::SHIFT self.__next_level_table_addr = addr end private :__next_level_table_addr= end # ARMv8 level 3 page descriptor. class Stage1PageDescriptor < BitField module UXN OFFSET = 54 NUMBITS = 1 FALSE = 0 TRUE = 1 end module PXN OFFSET = 53 NUMBITS = 1 FALSE = 0 TRUE = 1 end module OutputAddr OFFSET = 16 NUMBITS = 32 end module AF OFFSET = 10 NUMBITS = 1 FALSE = 0 TRUE = 1 end module SH OFFSET = 8 NUMBITS = 2 INNER_SHAREABLE = 0b11 end module AP OFFSET = 6 NUMBITS = 2 RW_EL1 = 0b00 RO_EL1 = 0b10 end module AttrIndx OFFSET = 2 NUMBITS = 3 end module Type OFFSET = 1 NUMBITS = 1 RESERVED_INVALID = 0 PAGE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def output_addr=(addr) addr >>= Granule64KiB::SHIFT self.__output_addr = addr end private :__output_addr= end # Translation table representing the structure defined in translation_table.rs. class TranslationTable module MAIR NORMAL = 1 end def initialize do_sanity_checks num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) populate_lvl2_entries end def map_at(virt_region, phys_region, attributes) return if virt_region.empty? raise if virt_region.size != phys_region.size raise if phys_region.last > BSP.phys_addr_space_end_page virt_region.zip(phys_region).each do |virt_page, phys_page| desc = page_descriptor_from(virt_page) set_lvl3_entry(desc, phys_page, attributes) end end def to_binary data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) data.pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr_binary [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr @lvl2_phys_start_addr end private def do_sanity_checks raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? end def new_lvl3(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do temp = CArray.new(start_addr, 8192) do Stage1PageDescriptor.new end start_addr += temp.size_in_byte temp end end def new_lvl2(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do Stage1TableDescriptor.new end end def populate_lvl2_entries @lvl2.each_with_index do |descriptor, i| descriptor.next_level_table_addr = @lvl3[i].phys_start_addr descriptor.type = Stage1TableDescriptor::Type::TABLE descriptor.valid = Stage1TableDescriptor::Valid::TRUE end end def lvl2_lvl3_index_from(addr) addr -= BSP.kernel_virt_start_addr lvl2_index = addr >> Granule512MiB::SHIFT lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT raise unless lvl2_index < @lvl2.size [lvl2_index, lvl3_index] end def page_descriptor_from(virt_addr) lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) @lvl3[lvl2_index][lvl3_index] end # rubocop:disable Metrics/MethodLength def set_attributes(desc, attributes) case attributes.mem_attributes when :CacheableDRAM desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE desc.attr_indx = MAIR::NORMAL else raise 'Invalid input' end desc.ap = case attributes.acc_perms when :ReadOnly Stage1PageDescriptor::AP::RO_EL1 when :ReadWrite Stage1PageDescriptor::AP::RW_EL1 else raise 'Invalid input' end desc.pxn = if attributes.execute_never Stage1PageDescriptor::PXN::TRUE else Stage1PageDescriptor::PXN::FALSE end desc.uxn = Stage1PageDescriptor::UXN::TRUE end # rubocop:enable Metrics/MethodLength def set_lvl3_entry(desc, output_addr, attributes) desc.output_addr = output_addr desc.af = Stage1PageDescriptor::AF::TRUE desc.type = Stage1PageDescriptor::Type::PAGE desc.valid = Stage1PageDescriptor::Valid::TRUE set_attributes(desc, attributes) end end end end ================================================ FILE: 19_kernel_heap/tools/translation_table_tool/bsp.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/tools/translation_table_tool/generic.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/tools/translation_table_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 19_kernel_heap/tools/translation_table_tool/main.rb ================================================ #!/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" ================================================ FILE: 20_timer_callbacks/.cargo/config.toml ================================================ [target.'cfg(target_os = "none")'] runner = "target/kernel_test_runner.sh" ================================================ FILE: 20_timer_callbacks/.vscode/settings.json ================================================ { "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 } ================================================ FILE: 20_timer_callbacks/Cargo.toml ================================================ [workspace] members = [ "libraries/*", "kernel", "kernel_symbols" ] [profile.release] lto = true debug = true ================================================ FILE: 20_timer_callbacks/Makefile ================================================ ## 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 ================================================ FILE: 20_timer_callbacks/README.md ================================================ # 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' ``` ================================================ FILE: 20_timer_callbacks/kernel/Cargo.toml ================================================ [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 ================================================ FILE: 20_timer_callbacks/kernel/build.rs ================================================ 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())); } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/backtrace.rs ================================================ // 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); } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/cpu/boot.s ================================================ // 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 ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/cpu/smp.rs ================================================ // 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) } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/cpu.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/exception/asynchronous.rs ================================================ // 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::())); } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/exception.rs ================================================ // 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); } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/exception.s ================================================ // 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 ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu/translation_table.rs ================================================ // 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::() ); } } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/memory/mmu.rs ================================================ // 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) } } ================================================ FILE: 20_timer_callbacks/kernel/src/_arch/aarch64/time.rs ================================================ // 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); } ================================================ FILE: 20_timer_callbacks/kernel/src/backtrace.rs ================================================ // 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, " ----------------------------------------------------------------------------------------------" ) } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicc.rs ================================================ // 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)); } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2/gicd.rs ================================================ // 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); }); } } } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/arm/gicv2.rs ================================================ // 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()); } } }); } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/arm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! ARM driver top level. pub mod gicv2; pub use gicv2::*; ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // 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 } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/local_ic.rs ================================================ // 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()); } } }); } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller/peripheral_ic.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Peripheral Interrupt Controller Driver. //! //! # Resources //! //! - use super::{PendingIRQs, PeripheralIRQ}; use crate::{ bsp::device_driver::common::MMIODerefWrapper, exception, memory::{Address, Virtual}, synchronization, synchronization::{IRQSafeNullLock, InitStateLock}, }; use alloc::vec::Vec; use tock_registers::{ interfaces::{Readable, Writeable}, register_structs, registers::{ReadOnly, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- register_structs! { #[allow(non_snake_case)] WORegisterBlock { (0x00 => _reserved1), (0x10 => ENABLE_1: WriteOnly), (0x14 => ENABLE_2: WriteOnly), (0x18 => @END), } } register_structs! { #[allow(non_snake_case)] RORegisterBlock { (0x00 => _reserved1), (0x04 => PENDING_1: ReadOnly), (0x08 => PENDING_2: ReadOnly), (0x0c => @END), } } /// Abstraction for the WriteOnly parts of the associated MMIO registers. type WriteOnlyRegisters = MMIODerefWrapper; /// Abstraction for the ReadOnly parts of the associated MMIO registers. type ReadOnlyRegisters = MMIODerefWrapper; type HandlerTable = Vec>>; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the peripheral interrupt controller. pub struct PeripheralIC { /// Access to write registers is guarded with a lock. wo_registers: IRQSafeNullLock, /// Register read access is unguarded. ro_registers: ReadOnlyRegisters, /// Stores registered IRQ handlers. Writable only during kernel init. RO afterwards. handler_table: InitStateLock, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PeripheralIC { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { wo_registers: IRQSafeNullLock::new(WriteOnlyRegisters::new(mmio_start_addr)), ro_registers: ReadOnlyRegisters::new(mmio_start_addr), handler_table: InitStateLock::new(Vec::new()), } } /// Called by the kernel to bring up the device. pub fn init(&self) { self.handler_table .write(|table| table.resize(PeripheralIRQ::MAX_INCLUSIVE + 1, None)); } /// Query the list of pending IRQs. fn pending_irqs(&self) -> PendingIRQs { let pending_mask: u64 = (u64::from(self.ro_registers.PENDING_2.get()) << 32) | u64::from(self.ro_registers.PENDING_1.get()); PendingIRQs::new(pending_mask) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::{Mutex, ReadWriteEx}; impl exception::asynchronous::interface::IRQManager for PeripheralIC { type IRQNumberType = PeripheralIRQ; fn register_handler( &self, irq_handler_descriptor: exception::asynchronous::IRQHandlerDescriptor, ) -> Result<(), &'static str> { self.handler_table.write(|table| { let irq_number = irq_handler_descriptor.number().get(); if table[irq_number].is_some() { return Err("IRQ handler already registered"); } table[irq_number] = Some(irq_handler_descriptor); Ok(()) }) } fn enable(&self, irq: &Self::IRQNumberType) { self.wo_registers.lock(|regs| { let enable_reg = if irq.get() <= 31 { ®s.ENABLE_1 } else { ®s.ENABLE_2 }; let enable_bit: u32 = 1 << (irq.get() % 32); // Writing a 1 to a bit will set the corresponding IRQ enable bit. All other IRQ enable // bits are unaffected. So we don't need read and OR'ing here. enable_reg.set(enable_bit); }); } fn handle_pending_irqs<'irq_context>( &'irq_context self, _ic: &exception::asynchronous::IRQContext<'irq_context>, ) { self.handler_table.read(|table| { for irq_number in self.pending_irqs() { match table[irq_number] { None => panic!("No handler registered for IRQ {}", irq_number), Some(descriptor) => { // Call the IRQ handler. Panics on failure. descriptor.handler().handle().expect("Error handling IRQ"); } } } }) } fn print_handler(&self) { use crate::info; info!(" Peripheral handler:"); self.handler_table.read(|table| { for (i, opt) in table.iter().enumerate() { if let Some(handler) = opt { info!(" {: >3}. {}", i, handler.name()); } } }); } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_interrupt_controller.rs ================================================ // 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(); } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, exception::{self, asynchronous::IRQNumber}, memory::{Address, Virtual}, synchronization, synchronization::IRQSafeNullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt FIFO Level Select Register. IFLS [ /// Receive interrupt FIFO level select. The trigger points for the receive interrupt are as /// follows. RXIFLSEL OFFSET(3) NUMBITS(5) [ OneEigth = 0b000, OneQuarter = 0b001, OneHalf = 0b010, ThreeQuarters = 0b011, SevenEights = 0b100 ] ], /// Interrupt Mask Set/Clear Register. IMSC [ /// Receive timeout interrupt mask. A read returns the current mask for the UARTRTINTR /// interrupt. /// /// - On a write of 1, the mask of the UARTRTINTR interrupt is set. /// - A write of 0 clears the mask. RTIM OFFSET(6) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Receive interrupt mask. A read returns the current mask for the UARTRXINTR interrupt. /// /// - On a write of 1, the mask of the UARTRXINTR interrupt is set. /// - A write of 0 clears the mask. RXIM OFFSET(4) NUMBITS(1) [ Disabled = 0, Enabled = 1 ] ], /// Masked Interrupt Status Register. MIS [ /// Receive timeout masked interrupt status. Returns the masked interrupt state of the /// UARTRTINTR interrupt. RTMIS OFFSET(6) NUMBITS(1) [], /// Receive masked interrupt status. Returns the masked interrupt state of the UARTRXINTR /// interrupt. RXMIS OFFSET(4) NUMBITS(1) [] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => IFLS: ReadWrite), (0x38 => IMSC: ReadWrite), (0x3C => _reserved3), (0x40 => MIS: ReadOnly), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: IRQSafeNullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Set RX FIFO fill level at 1/8. self.registers.IFLS.write(IFLS::RXIFLSEL::OneEigth); // Enable RX IRQ + RX timeout IRQ. self.registers .IMSC .write(IMSC::RXIM::Enabled + IMSC::RTIM::Enabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Send a slice of characters. fn write_array(&mut self, a: &[char]) { for c in a { self.write_char(*c); } } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: Address) -> Self { Self { inner: IRQSafeNullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { type IRQNumberType = IRQNumber; fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } fn register_and_enable_irq_handler( &'static self, irq_number: &Self::IRQNumberType, ) -> Result<(), &'static str> { use exception::asynchronous::{irq_manager, IRQHandlerDescriptor}; let descriptor = IRQHandlerDescriptor::new(*irq_number, Self::COMPATIBLE, self); irq_manager().register_handler(descriptor)?; irq_manager().enable(irq_number); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_array(&self, a: &[char]) { self.inner.lock(|inner| inner.write_array(a)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} impl exception::asynchronous::interface::IRQHandler for PL011Uart { fn handle(&self) -> Result<(), &'static str> { self.inner.lock(|inner| { let pending = inner.registers.MIS.extract(); // Clear all pending IRQs. inner.registers.ICR.write(ICR::ALL::CLEAR); // Check for any kind of RX interrupt. if pending.matches_any(MIS::RXMIS::SET + MIS::RTMIS::SET) { // Echo any received characters. while let Some(c) = inner.read_char_converting(BlockingMode::NonBlocking) { inner.write_char(c) } } }); Ok(()) } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/bcm.rs ================================================ // 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::*; ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver/common.rs ================================================ // 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) } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/device_driver.rs ================================================ // 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::*; ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/driver.rs ================================================ // 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()); }; } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/exception/asynchronous.rs ================================================ // 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); } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/exception.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! BSP synchronous and asynchronous exception handling. pub mod asynchronous; ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/kernel_virt_addr_space_size.ld ================================================ __kernel_virt_addr_space_size = 1024 * 1024 * 1024 ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/memory/mmu.rs ================================================ // 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()), ); } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi/memory.rs ================================================ // 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) } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp/raspberrypi.rs ================================================ // 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" } } ================================================ FILE: 20_timer_callbacks/kernel/src/bsp.rs ================================================ // 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::*; ================================================ FILE: 20_timer_callbacks/kernel/src/common.rs ================================================ // 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") } } ================================================ FILE: 20_timer_callbacks/kernel/src/console/buffer_console.rs ================================================ // 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 {} ================================================ FILE: 20_timer_callbacks/kernel/src/console.rs ================================================ // 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) } ================================================ FILE: 20_timer_callbacks/kernel/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: 20_timer_callbacks/kernel/src/cpu/smp.rs ================================================ // 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; ================================================ FILE: 20_timer_callbacks/kernel/src/cpu.rs ================================================ // 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}; ================================================ FILE: 20_timer_callbacks/kernel/src/driver.rs ================================================ // 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()); } }); } } ================================================ FILE: 20_timer_callbacks/kernel/src/exception/asynchronous/null_irq_manager.rs ================================================ // 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"); } } ================================================ FILE: 20_timer_callbacks/kernel/src/exception/asynchronous.rs ================================================ // 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) } ================================================ FILE: 20_timer_callbacks/kernel/src/exception.rs ================================================ // 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) } } ================================================ FILE: 20_timer_callbacks/kernel/src/lib.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/src/main.rs ================================================ // 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(); } ================================================ FILE: 20_timer_callbacks/kernel/src/memory/heap_alloc.rs ================================================ // 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); } ================================================ FILE: 20_timer_callbacks/kernel/src/memory/mmu/mapping_record.rs ================================================ // 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()); } ================================================ FILE: 20_timer_callbacks/kernel/src/memory/mmu/page_alloc.rs ================================================ // 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) } } ================================================ FILE: 20_timer_callbacks/kernel/src/memory/mmu/translation_table.rs ================================================ // 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)); } } ================================================ FILE: 20_timer_callbacks/kernel/src/memory/mmu/types.rs ================================================ // 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 ); } } } ================================================ FILE: 20_timer_callbacks/kernel/src/memory/mmu.rs ================================================ // 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) } ================================================ FILE: 20_timer_callbacks/kernel/src/memory.rs ================================================ // 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); } } ================================================ FILE: 20_timer_callbacks/kernel/src/panic_wait.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/src/print.rs ================================================ // 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)* )); } }) } ================================================ FILE: 20_timer_callbacks/kernel/src/state.rs ================================================ // 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"); } } } ================================================ FILE: 20_timer_callbacks/kernel/src/symbols.rs ================================================ // 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"); } } ================================================ FILE: 20_timer_callbacks/kernel/src/synchronization.rs ================================================ // 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::()); } } ================================================ FILE: 20_timer_callbacks/kernel/src/time.rs ================================================ // 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(()) } } ================================================ FILE: 20_timer_callbacks/kernel/tests/00_console_sanity.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/kernel/tests/00_console_sanity.rs ================================================ // 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(); } ================================================ FILE: 20_timer_callbacks/kernel/tests/01_timer_sanity.rs ================================================ // 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) } ================================================ FILE: 20_timer_callbacks/kernel/tests/02_exception_sync_page_fault.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/kernel/tests/03_exception_restore_sanity.rs ================================================ // 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(); } ================================================ FILE: 20_timer_callbacks/kernel/tests/04_exception_irq_sanity.rs ================================================ // 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()); } ================================================ FILE: 20_timer_callbacks/kernel/tests/05_backtrace_sanity.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/kernel/tests/05_backtrace_sanity.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/kernel/tests/06_backtrace_invalid_frame.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/kernel/tests/07_backtrace_invalid_link.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Once 5' ================================================ FILE: 20_timer_callbacks/kernel/tests/panic_exit_success/mod.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel/tests/panic_wait_forever/mod.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/kernel_symbols/Cargo.toml ================================================ [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" } ================================================ FILE: 20_timer_callbacks/kernel_symbols/build.rs ================================================ 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() ); } ================================================ FILE: 20_timer_callbacks/kernel_symbols/kernel_symbols.ld ================================================ /* 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*) } } ================================================ FILE: 20_timer_callbacks/kernel_symbols/src/main.rs ================================================ // 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!() } ================================================ FILE: 20_timer_callbacks/kernel_symbols.mk ================================================ ## 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 ================================================ FILE: 20_timer_callbacks/libraries/debug-symbol-types/Cargo.toml ================================================ [package] name = "debug-symbol-types" version = "0.1.0" edition = "2021" ================================================ FILE: 20_timer_callbacks/libraries/debug-symbol-types/src/lib.rs ================================================ // 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 } } ================================================ FILE: 20_timer_callbacks/libraries/test-macros/Cargo.toml ================================================ [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" } ================================================ FILE: 20_timer_callbacks/libraries/test-macros/src/lib.rs ================================================ // 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() } ================================================ FILE: 20_timer_callbacks/libraries/test-types/Cargo.toml ================================================ [package] name = "test-types" version = "0.1.0" authors = ["Andre Richter "] edition = "2021" ================================================ FILE: 20_timer_callbacks/libraries/test-types/src/lib.rs ================================================ // 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(), } ================================================ FILE: 20_timer_callbacks/tools/kernel_symbols_tool/cmds.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/tools/kernel_symbols_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/tools/kernel_symbols_tool/main.rb ================================================ #!/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 ================================================ FILE: 20_timer_callbacks/tools/translation_table_tool/arch.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter # Bitfield manipulation. class BitField def initialize @value = 0 end def self.attr_bitfield(name, offset, num_bits) define_method("#{name}=") do |bits| mask = (2**num_bits) - 1 raise "Input out of range: #{name} = 0x#{bits.to_s(16)}" if (bits & ~mask).positive? # Clear bitfield @value &= ~(mask << offset) # Set it @value |= (bits << offset) end end def to_i @value end def size_in_byte 8 end end # An array class that knows its memory location. class CArray < Array attr_reader :phys_start_addr def initialize(phys_start_addr, size, &block) @phys_start_addr = phys_start_addr super(size, &block) end def size_in_byte inject(0) { |sum, n| sum + n.size_in_byte } end end #--------------------------------------------------------------------------------------------------- # Arch:: #--------------------------------------------------------------------------------------------------- module Arch #--------------------------------------------------------------------------------------------------- # Arch::ARMv8 #--------------------------------------------------------------------------------------------------- module ARMv8 # ARMv8 Table Descriptor. class Stage1TableDescriptor < BitField module NextLevelTableAddr OFFSET = 16 NUMBITS = 32 end module Type OFFSET = 1 NUMBITS = 1 BLOCK = 0 TABLE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:__next_level_table_addr, NextLevelTableAddr::OFFSET, NextLevelTableAddr::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def next_level_table_addr=(addr) addr >>= Granule64KiB::SHIFT self.__next_level_table_addr = addr end private :__next_level_table_addr= end # ARMv8 level 3 page descriptor. class Stage1PageDescriptor < BitField module UXN OFFSET = 54 NUMBITS = 1 FALSE = 0 TRUE = 1 end module PXN OFFSET = 53 NUMBITS = 1 FALSE = 0 TRUE = 1 end module OutputAddr OFFSET = 16 NUMBITS = 32 end module AF OFFSET = 10 NUMBITS = 1 FALSE = 0 TRUE = 1 end module SH OFFSET = 8 NUMBITS = 2 INNER_SHAREABLE = 0b11 end module AP OFFSET = 6 NUMBITS = 2 RW_EL1 = 0b00 RO_EL1 = 0b10 end module AttrIndx OFFSET = 2 NUMBITS = 3 end module Type OFFSET = 1 NUMBITS = 1 RESERVED_INVALID = 0 PAGE = 1 end module Valid OFFSET = 0 NUMBITS = 1 FALSE = 0 TRUE = 1 end attr_bitfield(:uxn, UXN::OFFSET, UXN::NUMBITS) attr_bitfield(:pxn, PXN::OFFSET, PXN::NUMBITS) attr_bitfield(:__output_addr, OutputAddr::OFFSET, OutputAddr::NUMBITS) attr_bitfield(:af, AF::OFFSET, AF::NUMBITS) attr_bitfield(:sh, SH::OFFSET, SH::NUMBITS) attr_bitfield(:ap, AP::OFFSET, AP::NUMBITS) attr_bitfield(:attr_indx, AttrIndx::OFFSET, AttrIndx::NUMBITS) attr_bitfield(:type, Type::OFFSET, Type::NUMBITS) attr_bitfield(:valid, Valid::OFFSET, Valid::NUMBITS) def output_addr=(addr) addr >>= Granule64KiB::SHIFT self.__output_addr = addr end private :__output_addr= end # Translation table representing the structure defined in translation_table.rs. class TranslationTable module MAIR NORMAL = 1 end def initialize do_sanity_checks num_lvl2_tables = BSP.kernel_virt_addr_space_size >> Granule512MiB::SHIFT @lvl3 = new_lvl3(num_lvl2_tables, BSP.phys_addr_of_kernel_tables) @lvl2_phys_start_addr = @lvl3.phys_start_addr + @lvl3.size_in_byte @lvl2 = new_lvl2(num_lvl2_tables, @lvl2_phys_start_addr) populate_lvl2_entries end def map_at(virt_region, phys_region, attributes) return if virt_region.empty? raise if virt_region.size != phys_region.size raise if phys_region.last > BSP.phys_addr_space_end_page virt_region.zip(phys_region).each do |virt_page, phys_page| desc = page_descriptor_from(virt_page) set_lvl3_entry(desc, phys_page, attributes) end end def to_binary data = @lvl3.flatten.map(&:to_i) + @lvl2.map(&:to_i) data.pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr_binary [@lvl2_phys_start_addr].pack('Q<*') # "Q" == uint64_t, "<" == little endian end def phys_tables_base_addr @lvl2_phys_start_addr end private def do_sanity_checks raise unless BSP.kernel_granule::SIZE == Granule64KiB::SIZE raise unless (BSP.kernel_virt_addr_space_size % Granule512MiB::SIZE).zero? end def new_lvl3(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do temp = CArray.new(start_addr, 8192) do Stage1PageDescriptor.new end start_addr += temp.size_in_byte temp end end def new_lvl2(num_lvl2_tables, start_addr) CArray.new(start_addr, num_lvl2_tables) do Stage1TableDescriptor.new end end def populate_lvl2_entries @lvl2.each_with_index do |descriptor, i| descriptor.next_level_table_addr = @lvl3[i].phys_start_addr descriptor.type = Stage1TableDescriptor::Type::TABLE descriptor.valid = Stage1TableDescriptor::Valid::TRUE end end def lvl2_lvl3_index_from(addr) addr -= BSP.kernel_virt_start_addr lvl2_index = addr >> Granule512MiB::SHIFT lvl3_index = (addr & Granule512MiB::MASK) >> Granule64KiB::SHIFT raise unless lvl2_index < @lvl2.size [lvl2_index, lvl3_index] end def page_descriptor_from(virt_addr) lvl2_index, lvl3_index = lvl2_lvl3_index_from(virt_addr) @lvl3[lvl2_index][lvl3_index] end # rubocop:disable Metrics/MethodLength def set_attributes(desc, attributes) case attributes.mem_attributes when :CacheableDRAM desc.sh = Stage1PageDescriptor::SH::INNER_SHAREABLE desc.attr_indx = MAIR::NORMAL else raise 'Invalid input' end desc.ap = case attributes.acc_perms when :ReadOnly Stage1PageDescriptor::AP::RO_EL1 when :ReadWrite Stage1PageDescriptor::AP::RW_EL1 else raise 'Invalid input' end desc.pxn = if attributes.execute_never Stage1PageDescriptor::PXN::TRUE else Stage1PageDescriptor::PXN::FALSE end desc.uxn = Stage1PageDescriptor::UXN::TRUE end # rubocop:enable Metrics/MethodLength def set_lvl3_entry(desc, output_addr, attributes) desc.output_addr = output_addr desc.af = Stage1PageDescriptor::AF::TRUE desc.type = Stage1PageDescriptor::Type::PAGE desc.valid = Stage1PageDescriptor::Valid::TRUE set_attributes(desc, attributes) end end end end ================================================ FILE: 20_timer_callbacks/tools/translation_table_tool/bsp.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/tools/translation_table_tool/generic.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/tools/translation_table_tool/kernel_elf.rb ================================================ # 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 ================================================ FILE: 20_timer_callbacks/tools/translation_table_tool/main.rb ================================================ #!/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" ================================================ FILE: Gemfile ================================================ # frozen_string_literal: true source 'https://rubygems.org' gem 'colorize' gem 'elftools' group :uart do gem 'ruby-progressbar' gem 'serialport' end group :development do gem 'rubocop', '>= 1.38.0', require: false end ================================================ FILE: LICENSE-APACHE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: LICENSE-MIT ================================================ MIT License 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 in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.CN.md ================================================ # Rust 开发树莓派操作系统教程 ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi3/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi4/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Unit-Tests/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Integration-Tests/badge.svg) ![](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue)
## ℹ️ 介绍 该系列教程适用于 ARM64 位[ARMv8-A 架构]的业余操作系统开发者。该教程会从零开始,一步步地指导你如何开发一个[功能健全的] 嵌入式操作系统的内核。包含了实现一般操作系统的任务,例如开发串口控制台,设置虚拟内存和处理硬件异常。 同时利用 Rust 的特性来提供系统的安全和速度。 祝你玩得开心! _带上我最诚挚的问候,
Andre ([@andre-richter])_ [armv8-a 架构]: https://developer.arm.com/products/architecture/cpu-architecture/a-profile/docs [功能健全的]: https://en.wikipedia.org/wiki/Monolithic_kernel [@andre-richter]: https://github.com/andre-richter ## 📑 教程结构 - 每篇教程都包含一个独立可引导的二进制内核文件。 - 每篇新的教程都在之前的基础上扩展。 - 每篇教程的指南里面都有一个简短的章节来总结新增的代码和功能,也会展示源代码的区别,方便检查和同步。 - 部分教程中有除了`tl;dr`章节外还有非常详细、具体的介绍。长期计划是所有的教程都会有详细的文字说明。但是目前只有那些我认为教程的`tl;dr`和`diff`还不够详细的章节会详细说明。 - 教程中所用的代码可以在**树莓派 3 和 4**上运行。 - 教程的第一到五章是基础内容,只能运行在`QEMU`上。 - 到了[第六章]时(06_drivers_gpio_uart),你可以在树莓派上加载和运行内核并通过`UART`来观察输出结果。 - 虽然这些教程是以树莓派 3 和 4 为试验对象,但代码是模块化的,所以应该容易移植到其他 CPU 架构的开发板上。 - 我希望会有人有机会去实现**RISC-V**架构的代码。 - 我推荐使用[Visual Studio Code],配置[Rust Analyzer]插件开发代码。 - 除了文本教程之外,也可以用`make doc`命令利用网页的优势来浏览代码。 ### `make doc` 的输出 ![make doc](doc/make_doc.png) [Visual Studio Code]: https://code.visualstudio.com [Rust Analyzer]: https://rust-analyzer.github.io ## 🛠 系统要求 本教程主要是面向**Linux**发行版的。理论上,文中大部分内容在其他类Unix系统诸如**macOS**也能正常工作,但请注意,只是理论上。 ### 🚀 tl;dr 版本 1. [安装 Docker][install_docker]。 2. **(仅限Linux)** 确保您的用户帐户在 [docker group] 中。 3. 准备Rust工具链。其中大部分将在首次使用时通过[rust-toolchain.toml](rust-toolchain.toml)文件进行处理。我们要做的是: 1. 如果你已经安装了一个版本的Rust: ```bash cargo install cargo-binutils rustfilt ``` 1. 如果你想要全新安装: ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env cargo install cargo-binutils rustfilt ``` 4. 如果你使用 `Visual Studio Code`,我强烈推荐你安装[Rust Analyzer 扩展]。 5. **(仅限macOS)** 安装一些`Ruby` gems。 这是作者最后一次在`macOS Monterey`上用`Ruby 3.0.2`版本进行测试。如果您正在使用`rbenv`,那么相应的`.ruby-version`文件已经就位。 如果你从未听说过`rbenv`,请尝试使用[这个指南](https://stackoverflow.com/a/68118750)。 在存储库根文件夹中运行此操作: ```bash bundle config set --local path '.vendor/bundle' bundle config set --local without 'development' bundle install ``` [docker group]: https://docs.docker.com/engine/install/linux-postinstall/ [Rust Analyzer 扩展]: https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer ## 🧰 长期版本: 消除工具链烦恼 这个系列的教程会着重关注用户体验的友好性。因此,我尽量消除嵌入式开发中的最大痛点:`Toolchain hassle`。 Rust内置的交叉编译支持在这方面帮了我们大忙。我们只需要使用`rustup`安装目标工具链就可以在`x86`宿主机上交叉编译支持树莓派的目标文件。然而,除了Rust编译器,我们还需要更多的工具。例如: Rust本身在这方面已经起到了很大的作用,因为它内置了对交叉编译的支持。从`x86`宿主机到树莓派的`AArch64`架构的交叉编译所需的一切都将由`rustup`自动安装。然而,除了Rust编译器,我们还将使用更多的工具。例如: - 用于在我们的宿主系统上模拟我们内核运行环境的`QEMU`。 - 一个叫`Minipush`的自制工具,可以通过`UART`将内核加载到树莓派上。 - 用于调式目标文件的`OpenOCD`和`GDB`。 在你的宿主机上安装/编译正确版本的上述工具很可能会遇到很多麻烦。举个例子,你的发行版也许并不会提供我们需要的最新版本的软件包。又或者你在编译这些工具时会遇到一些很难处理的依赖问题。 这也是为什么我们要尽可能使用[Docker][install_docker]的原因。我们提供了一个已经预装了所有需要的工具及依赖的容器,当需要的时候它就会被自动拉取。如果你想要了解更多有关Docker和这个容器的细节,请查看本仓库下的[docker](docker) 文件夹。 [install_docker]: https://docs.docker.com/get-docker/ ## 📟 USB 串行输出 由于教程中开发的内核是在真实的硬件上运行的,因此强烈建议您使用 USB 串行调试线来进行试验。连接调试线后,树莓派需要通过额外电源供电。 - 您可以在[\[1\]] [\[2\]]中或者[淘宝]上找到USB转串口线,但许多其他线材也可以工作。理想情况下,您的线材应基于`CP2102`芯片。 - 您将其连接到`GND`和GPIO引脚`14/15`,如下所示。 - [教程5](05_drivers_gpio_uart/README.CN.md)是这个设备第一次需要使用的地方。查看它了解如何准备SD卡以从中启动自制内核的说明。 - 从[教程6](06_uart_chainloader/README.CN.md)开始,在树莓派上启动内核变得非常舒适。在本教程中开发了一个所谓的`chainloader`,。 这将是您暂时需要在SD卡上手动复制的最后一个文件。这将使您能够在通过`UART`按需引导期间加载教程内核。 ![UART wiring diagram](doc/wiring.png) [\[1\]]: https://www.amazon.de/dp/B0757FQ5CX/ref=cm_sw_r_tw_dp_U_x_ozGRDbVTJAG4Q [\[2\]]: https://www.adafruit.com/product/954 [淘宝]: https://www.taobao.com/ ## 🙌 致谢 这个教程最初是由[Zoltan Baldaszti](https://github.com/bztsrc)的[项目](https://github.com/bztsrc/raspi3-tutorial)衍生出来的,感谢它给我开了一个头。 ## License Licensed under either of - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### 贡献 除非您明确声明,否则有意提交给您的任何贡献(包括 Apache-2.0 许可中定义的)均应按上述双重许可,且无任何附加条款或条件。 ================================================ FILE: README.ES.md ================================================ # Tutoriales de desarrollo de Sistemas Operativos en Rust con la Raspberry Pi ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi3/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi4/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Unit-Tests/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Integration-Tests/badge.svg) ![](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue)
## ℹ️ Introducción Esto es una serie de tutoriales para los desarrolladores aficionados a los Sistemas Operativos (OS) que se están adentrando a la nueva arquitectura ARM de 64 bits [ARMv8-A architecture]. Los tutoriales darán una guía paso a paso en cómo escribir un Sistema Operativo [monolítico] desde cero. Estos tutoriales cubren la implementación común de diferentes tareas de Sistemas Operativos, como escribir en una terminal serie, configurar la memoria virtual y manejar excepciones de hardware (HW). Todo mientras usamos la seguridad y velocidad que `Rust` nos proporciona. ¡Divértanse! _Atentamente,
Andre ([@andre-richter])_ P.S.: Para otros lenguajes, por favor busquen los diferentes archivos README. Por ejemplo, [`README.CN.md`](README.CN.md) o [`README.ES.md`](README.ES.md). Muchas gracias a nuestros [traductores](#traducciones-de-este-repositorio) 🙌. [ARMv8-A architecture]: https://developer.arm.com/products/architecture/cpu-architecture/a-profile/docs [monolítico]: https://en.wikipedia.org/wiki/Monolithic_kernel [@andre-richter]: https://github.com/andre-richter ## 📑 Estructura - Cada tutorial contiene un solo binario arrancable correspondiente al núcleo. - Cada tutorial nuevo extiende el tutorial anterior. - Cada tutorial tendrá un `README` y cada `README` tendrá un pequeña sección de [`tl;dr`](https://es.wikipedia.org/wiki/TL;DR) en donde se dará una pequeña perspectiva general de los cambios y se mostrará el código fuente `diff` del tutorial anterior para que se puedan inspeccionar los cambios/adiciones que han ocurrido. - Algunos tutoriales además de tener un `tl;dr` también tendrán una sección en la que se dará una explicación con todo lujo de detalle. El plan a largo plazo es que cada tutorial tenga una buena explicación además del `tl;dr` y el `diff`; pero por el momento los únicos tutoriales que gozan de una son los tutoriales en los que creo que el `tl;dr` y el `diff` no son suficientes para comprender lo que está pasando. - El código que se escribió en este tutorial soporta y corre en la **Raspberry Pi 3** y en la **Raspberry 4** - Del tutorial 1 hasta el 5 son tutoriales "preparatorios", por lo que este código solo tendrá sentido ejecutarlo en [`QEMU`](https://www.qemu.org/). - Cuando llegues al [tutorial 5](05_drivers_gpio_uart) podrás comenzar a cargar y a ejecutar el núcleo en una Raspeberry de verdad, y observar la salida serie (`UART`). - Aunque la Raspberry Pi 3 y 4 son las principales placas este código está escrito en un estilo modular, lo que permite una fácil portabilidad a otras arquitecturas de CPU o/y placas. - Me encantaría si alguien intentase adaptar este código en una arquitectura **RISC-V**. - Para la edición recomiendo [Visual Studio Code] con [Rust Analyzer]. - En adición al texto que aparece en los tutoriales también sería recomendable revisar el comando `make doc` en cada tutorial. Este comando te deja navegar el código documentado de una manera cómoda. ### Salida del comando `make doc` ![make doc](doc/make_doc.png) [Visual Studio Code]: https://code.visualstudio.com [Rust Analyzer]: https://rust-analyzer.github.io ## 🛠 Requisitos del sistema Estos tutoriales están dirigidos principalmente a distribuciones de **Linux**. Muchas de las cosas vistas aquí también funcionan en **macOS**, pero esto solo es _experimental_. ### 🚀 La versión tl;dr 1. [Instala Docker Desktop][install_docker]. 2. (**Solo para Linux**) Asegúrate de que la cuenta de tu usuario está en el [grupo `docker`][docker group]. 3. Prepara la `Rust` toolchain. La mayor parte se hará automáticamente durante el primer uso del archivo [rust-toolchain.toml](rust-toolchain.toml). Todo lo que nos queda hacer a nosotros es: i. Si ya tienes una versión de Rust instalada: ```bash cargo install cargo-binutils rustfilt ``` ii. Si necesitas instalar Rust desde cero: ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env cargo install cargo-binutils rustfilt ``` 4. En caso de que uses `Visual Studio Code`, recomiendo que instales la extensión [Rust Analyzer extension]. 5. (**Solo para macOS**) Instala algunas `Ruby` gems. Ejecuta esto en la carpeta root del repositorio: ```bash bundle install --path .vendor/bundle --without development ``` [docker group]: https://docs.docker.com/engine/install/linux-postinstall/ [Rust Analyzer extension]: https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer ### 🧰 Más detalles: Eliminando Lios con Toolchains Esta serie trata de enfocarse lo máximo posible en tener una experiencia agradable para el usuario. Por lo tanto, se han dirigido muchos esfuerzos a eliminar la parte más difícil del desarrollo de los sistemas incorporados (embedded) tanto como se pudo. Rust por sí mismo ya ayuda mucho, porque tiene integrado el soporte para compilación cruzada. Todo lo que necesitamos para compilar desde una máquina con una arquitectura `x86` a una Raspberry Pi con arquitectura `AArch64` será automáticamente instalado por `rustup`. Sin embargo, además de usar el compilador de Rust, también usaremos algunas otras herramientas, entre las cuales están: - `QEMU` para emular nuestro núcleo en nuestra máquina principal. - Una herramienta llamada `Minipush` para cargar el núcleo en una Raspberry Pi cuando queramos usando `UART`. - `OpenOCD` y `GDB` para hacer depuración ("debugging") en la máquina a instalar. Hay muchas cosas que pueden salir mal mientras instalamos y/o compilamos las versiones correctas de cada herramienta en tu máquina. Por ejemplo, tu distribución de Linux tal vez podría no proporcionar las versiones más recientes de paquetes que se necesiten. O tal vez te falten algunas dependencias para la compilar estas herramientas. Esta es la razón por la cual usaremos [Docker][install_docker] mientras sea posible. Te estamos proporcionando un contenedor que tiene todas las herramientas o dependencias preinstaladas. Si quieres saber más acerca de Docker y revisar el contenedor proporcionado, por favor revisa la carpeta [docker](docker) del repositorio. [install_docker]: https://docs.docker.com/get-docker/ ## 📟 Puerto Serie USB Ya que el núcleo desarrollado en este tutorial se ejecuta en hardware real, se recomienda que tengas un adaptador de puerto serie USB cable para sentir la experiencia completa. - Puedes encontrar estos cables que deberían funcionar sin ningún problema en [\[1\]] [\[2\]], pero hay muchos otros que pueden funcionar. Idealmente, tu cable estaría basado en el chip `CP2102`. - Lo conectas a los pines `GND` y `GPIO` `14/15` como se muestra en la parte inferior. - [Tutorial 5](05_drivers_gpio_uart) es la primera vez en la que lo vas usar. Revisa las instrucciones sobre cómo preparar una tarjeta SD para arrancar en tu núcleo desde ahí. - Empezando con el [tutorial 6](06_uart_chainloader), arrancar núcleos en tu Raspberry Pi comienza a ser más fácil. En este tutorial se desarrolla un `chainloader`, que será el último archivo que necesitarás copiar de manera manual a la tarjeta SD por el momento. Esto te permitirá cargar los núcleos de los tutoriales durante el arranque usando `UART`. ![UART wiring diagram](doc/wiring.png) [\[1\]]: https://www.amazon.de/dp/B0757FQ5CX/ref=cm_sw_r_tw_dp_U_x_ozGRDbVTJAG4Q [\[2\]]: https://www.adafruit.com/product/954 ## 🙌 Agradecimientos La versión original de estos tutoriales empezó como un fork de los increíbles [tutoriales de programación en hardware en la RPi3](https://github.com/bztsrc/raspi3-tutorial) en `C` de [Zoltan Baldaszti](https://github.com/bztsrc). ¡Gracias por darme un punto de partida! ### Traducciones de este repositorio - **Chino:** - [@colachg] y [@readlnh]. - Necesitan actualizaciones. - **Español:** - [@zanezhub]. - En el futuro habrán tutoriales traducidos al español. [@colachg]: https://github.com/colachg [@readlnh]: https://github.com/readlnh [@zanezhub]: https://github.com/zanezhub ## Licencia Este proyecto está licenciado por cualquiera de las siguientes licencias como alguna de tus dos opciones - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) o http://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) o http://opensource.org/licenses/MIT) ### Contribución A menos de que lo menciones, cualquier contribución enviada por ti para su inclusión en este trabajo, tal como se define en la licencia Apache-2.0, deberá tener doble licencia como se muestra en la parte superior, sin ningún cambio de términos o condiciones. ================================================ FILE: README.md ================================================ # Operating System development tutorials in Rust on the Raspberry Pi ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi3/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/BSP-RPi4/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Unit-Tests/badge.svg) ![](https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/workflows/Integration-Tests/badge.svg) ![](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue)
## ℹ️ Introduction This is a tutorial series for hobby OS developers who are new to ARM's 64 bit [ARMv8-A architecture]. The tutorials will give a guided, step-by-step tour of how to write a [monolithic] Operating System `kernel` for an `embedded system` from scratch. They cover implementation of common Operating Systems tasks, like writing to the serial console, setting up virtual memory and handling HW exceptions. All while leveraging `Rust`'s unique features to provide for safety and speed. Have fun! _Best regards,
Andre ([@andre-richter])_ P.S.: For other languages, please look out for alternative README files. For example, [`README.CN.md`](README.CN.md) or [`README.ES.md`](README.ES.md). Many thanks to our [translators](#translations-of-this-repository) 🙌. [ARMv8-A architecture]: https://developer.arm.com/products/architecture/cpu-architecture/a-profile/docs [monolithic]: https://en.wikipedia.org/wiki/Monolithic_kernel [@andre-richter]: https://github.com/andre-richter ## 📑 Organization - Each tutorial contains a stand-alone, bootable `kernel` binary. - Each new tutorial extends the previous one. - Each tutorial `README` will have a short `tl;dr` section giving a brief overview of the additions, and show the source code `diff` to the previous tutorial, so that you can conveniently inspect the changes/additions. - Some tutorials have a full-fledged, detailed text in addition to the `tl;dr` section. The long-term plan is that all tutorials get a full text, but for now this is exclusive to tutorials where I think that `tl;dr` and `diff` are not enough to get the idea. - The code written in these tutorials supports and runs on the **Raspberry Pi 3** and the **Raspberry Pi 4**. - Tutorials 1 till 5 are groundwork code which only makes sense to run in `QEMU`. - Starting with [tutorial 5](05_drivers_gpio_uart), you can load and run the kernel on the real Raspberrys and observe output over `UART`. - Although the Raspberry Pi 3 and 4 are the main target boards, the code is written in a modular fashion which allows for easy porting to other CPU architectures and/or boards. - I would really love if someone takes a shot at a **RISC-V** implementation! - For editing, I recommend [Visual Studio Code] with [Rust Analyzer]. - In addition to the tutorial text, also check out the `make doc` command in each tutorial. It lets you browse the extensively documented code in a convenient way. ### Output of `make doc` ![make doc](doc/make_doc.png) [Visual Studio Code]: https://code.visualstudio.com [Rust Analyzer]: https://rust-analyzer.github.io ## 🛠 System Requirements The tutorials are primarily targeted at **Linux**-based distributions. Most stuff will also work on **macOS**, but this is only _experimental_. ### 🚀 The tl;dr Version 1. [Install Docker Engine][install_docker]. 1. (**Linux only**) Ensure your user account is in the [docker group]. 1. Prepare the `Rust` toolchain. Most of it will be handled on first use through the [rust-toolchain.toml](rust-toolchain.toml) file. What's left for us to do is: 1. If you already have a version of Rust installed: ```bash cargo install cargo-binutils rustfilt ``` 1. If you need to install Rust from scratch: ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env cargo install cargo-binutils rustfilt ``` 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 config set --local path '.vendor/bundle' bundle config set --local without 'development' bundle install ``` [docker group]: https://docs.docker.com/engine/install/linux-postinstall/ [Rust Analyzer extension]: https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer ### 🧰 More Details: Eliminating Toolchain Hassle This series tries to put a strong focus on user friendliness. Therefore, efforts were made to eliminate the biggest painpoint in embedded development as much as possible: `Toolchain hassle`. Rust itself is already helping a lot in that regard, because it has built-in support for cross-compilation. All that we need for cross-compiling from an `x86` host to the Raspberry Pi's `AArch64` architecture will be automatically installed by `rustup`. However, besides the Rust compiler, we will use some more tools. Among others: - `QEMU` to emulate our kernel on the host system. - A self-made tool called `Minipush` to load a kernel onto the Raspberry Pi on-demand over `UART`. - `OpenOCD` and `GDB` for debugging on the target. There is a lot that can go wrong while installing and/or compiling the correct version of each tool on your host machine. For example, your distribution might not provide the latest version that is needed. Or you are missing some hard-to-get dependencies for the compilation of one of these tools. This is why we will make use of [Docker][install_docker] whenever possible. We are providing an accompanying container that has all the needed tools or dependencies pre-installed, and it gets 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/engine/install/#server ## 📟 USB Serial Output Since the kernel developed in the tutorials runs on the real hardware, it is highly recommended to get a USB serial cable to get the full experience. - You can find USB-to-serial cables that should work right away at [\[1\]] [\[2\]], but many others will work too. Ideally, your cable is based on the `CP2102` chip. - You connect it to `GND` and GPIO pins `14/15` as shown below. - [Tutorial 5](05_drivers_gpio_uart) is the first where you can use it. Check it out for instructions on how to prepare the SD card to boot your self-made kernel from it. - Starting with [tutorial 6](06_uart_chainloader), booting kernels on your Raspberry is getting _really_ comfortable. In this tutorial, a so-called `chainloader` is developed, which will be the last file you need to manually copy on the SD card for a while. It will enable you to load the tutorial kernels during boot on demand over `UART`. ![UART wiring diagram](doc/wiring.png) [\[1\]]: https://www.amazon.de/dp/B0757FQ5CX/ref=cm_sw_r_tw_dp_U_x_ozGRDbVTJAG4Q [\[2\]]: https://www.adafruit.com/product/954 ## 🙌 Acknowledgements The original version of the tutorials started out as a fork of [Zoltan Baldaszti](https://github.com/bztsrc)'s awesome [tutorials on bare metal programming on RPi3](https://github.com/bztsrc/raspi3-tutorial) in `C`. Thanks for giving me a head start! ### Translations of this repository - **Chinese** - [@colachg] and [@readlnh]. - Need updating. - **Spanish** - [@zanezhub]. - In the future there'll be tutorials translated to spanish. [@colachg]: https://github.com/colachg [@readlnh]: https://github.com/readlnh [@zanezhub]: https://github.com/zanezhub ## License Licensed under either of - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or ) - MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. ================================================ FILE: SPONSORING.md ================================================ # 💖 Sponsoring the Developers This repository is the result of the combined efforts of a large number of developers - in terms of writing the source code, but also in performing code reviews, writing documentation, and handling issues and PRs. Some of these developers received a salary or other payment from a third-party for their contributions. Others receive no payment of any kind, and simply hope that others find their contributions useful. If you would like to support any of the developers, please take a moment to [click through to their profiles] to see if they accept sponsorship and/or charitable gifts made in their name. [click through to their profiles]: https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials/graphs/contributors ================================================ FILE: X1_JTAG_boot/.vscode/settings.json ================================================ { "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 } ================================================ FILE: X1_JTAG_boot/Cargo.toml ================================================ [package] name = "mingo" version = "0.8.0" authors = ["Andre Richter "] edition = "2021" [profile.release] lto = true [features] default = [] bsp_rpi3 = ["tock-registers"] bsp_rpi4 = ["tock-registers"] [[bin]] name = "kernel" path = "src/main.rs" ##-------------------------------------------------------------------------------------------------- ## Dependencies ##-------------------------------------------------------------------------------------------------- [dependencies] # Optional dependencies tock-registers = { version = "0.8.x", default-features = false, features = ["register_types"], optional = true } # Platform specific dependencies [target.'cfg(target_arch = "aarch64")'.dependencies] aarch64-cpu = { version = "9.x.x" } ================================================ FILE: X1_JTAG_boot/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2018-2023 Andre Richter include ../common/docker.mk include ../common/format.mk include ../common/operating_system.mk ##-------------------------------------------------------------------------------------------------- ## Optional, user-provided configuration values ##-------------------------------------------------------------------------------------------------- # Default to the RPi3. BSP ?= rpi3 # Default to a serial device name that is common in Linux. DEV_SERIAL ?= /dev/ttyUSB0 ##-------------------------------------------------------------------------------------------------- ## BSP-specific configuration values ##-------------------------------------------------------------------------------------------------- QEMU_MISSING_STRING = "This board is not yet supported for QEMU." ifeq ($(BSP),rpi3) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = raspi3 QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a53 else ifeq ($(BSP),rpi4) TARGET = aarch64-unknown-none-softfloat KERNEL_BIN = kernel8.img QEMU_BINARY = qemu-system-aarch64 QEMU_MACHINE_TYPE = QEMU_RELEASE_ARGS = -serial stdio -display none OBJDUMP_BINARY = aarch64-none-elf-objdump NM_BINARY = aarch64-none-elf-nm READELF_BINARY = aarch64-none-elf-readelf LD_SCRIPT_PATH = $(shell pwd)/src/bsp/raspberrypi RUSTC_MISC_ARGS = -C target-cpu=cortex-a72 endif # Export for build.rs. export LD_SCRIPT_PATH ##-------------------------------------------------------------------------------------------------- ## Targets and Prerequisites ##-------------------------------------------------------------------------------------------------- KERNEL_MANIFEST = Cargo.toml KERNEL_LINKER_SCRIPT = kernel.ld LAST_BUILD_CONFIG = target/$(BSP).build_config KERNEL_ELF = target/$(TARGET)/release/kernel # This parses cargo's dep-info file. # https://doc.rust-lang.org/cargo/guide/build-cache.html#dep-info-files KERNEL_ELF_DEPS = $(filter-out %: ,$(file < $(KERNEL_ELF).d)) $(KERNEL_MANIFEST) $(LAST_BUILD_CONFIG) ##-------------------------------------------------------------------------------------------------- ## Command building blocks ##-------------------------------------------------------------------------------------------------- RUSTFLAGS = $(RUSTC_MISC_ARGS) \ -C link-arg=--library-path=$(LD_SCRIPT_PATH) \ -C link-arg=--script=$(KERNEL_LINKER_SCRIPT) RUSTFLAGS_PEDANTIC = $(RUSTFLAGS) \ -D warnings \ -D missing_docs FEATURES = --features bsp_$(BSP) COMPILER_ARGS = --target=$(TARGET) \ $(FEATURES) \ --release RUSTC_CMD = cargo rustc $(COMPILER_ARGS) DOC_CMD = cargo doc $(COMPILER_ARGS) CLIPPY_CMD = cargo clippy $(COMPILER_ARGS) OBJCOPY_CMD = rust-objcopy \ --strip-all \ -O binary EXEC_QEMU = $(QEMU_BINARY) -M $(QEMU_MACHINE_TYPE) EXEC_TEST_DISPATCH = ruby ../common/tests/dispatch.rb EXEC_MINIPUSH = ruby ../common/serial/minipush.rb ##------------------------------------------------------------------------------ ## Dockerization ##------------------------------------------------------------------------------ DOCKER_CMD = docker run -t --rm -v $(shell pwd):/work/tutorial -w /work/tutorial DOCKER_CMD_INTERACT = $(DOCKER_CMD) -i DOCKER_ARG_DIR_COMMON = -v $(shell pwd)/../common:/work/common DOCKER_ARG_DEV = --privileged -v /dev:/dev # DOCKER_IMAGE defined in include file (see top of this file). DOCKER_QEMU = $(DOCKER_CMD_INTERACT) $(DOCKER_IMAGE) DOCKER_TOOLS = $(DOCKER_CMD) $(DOCKER_IMAGE) DOCKER_TEST = $(DOCKER_CMD) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) # Dockerize commands, which require USB device passthrough, only on Linux. ifeq ($(shell uname -s),Linux) DOCKER_CMD_DEV = $(DOCKER_CMD_INTERACT) $(DOCKER_ARG_DEV) DOCKER_CHAINBOOT = $(DOCKER_CMD_DEV) $(DOCKER_ARG_DIR_COMMON) $(DOCKER_IMAGE) endif ##-------------------------------------------------------------------------------------------------- ## Targets ##-------------------------------------------------------------------------------------------------- .PHONY: all doc qemu chainboot clippy clean readelf objdump nm check all: $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Save the configuration as a file, so make understands if it changed. ##------------------------------------------------------------------------------ $(LAST_BUILD_CONFIG): @rm -f target/*.build_config @mkdir -p target @touch $(LAST_BUILD_CONFIG) ##------------------------------------------------------------------------------ ## Compile the kernel ELF ##------------------------------------------------------------------------------ $(KERNEL_ELF): $(KERNEL_ELF_DEPS) $(call color_header, "Compiling kernel ELF - $(BSP)") @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(RUSTC_CMD) ##------------------------------------------------------------------------------ ## Generate the stripped kernel binary ##------------------------------------------------------------------------------ $(KERNEL_BIN): $(KERNEL_ELF) $(call color_header, "Generating stripped binary") @$(OBJCOPY_CMD) $(KERNEL_ELF) $(KERNEL_BIN) $(call color_progress_prefix, "Name") @echo $(KERNEL_BIN) $(call color_progress_prefix, "Size") $(call disk_usage_KiB, $(KERNEL_BIN)) ##------------------------------------------------------------------------------ ## Generate the documentation ##------------------------------------------------------------------------------ doc: $(call color_header, "Generating docs") @$(DOC_CMD) --document-private-items --open ##------------------------------------------------------------------------------ ## Run the kernel in QEMU ##------------------------------------------------------------------------------ ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. qemu: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. qemu: $(KERNEL_BIN) $(call color_header, "Launching QEMU") @$(DOCKER_QEMU) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) endif ##------------------------------------------------------------------------------ ## Push the kernel to the real HW target ##------------------------------------------------------------------------------ chainboot: $(KERNEL_BIN) @$(DOCKER_CHAINBOOT) $(EXEC_MINIPUSH) $(DEV_SERIAL) $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run clippy ##------------------------------------------------------------------------------ clippy: @RUSTFLAGS="$(RUSTFLAGS_PEDANTIC)" $(CLIPPY_CMD) ##------------------------------------------------------------------------------ ## Clean ##------------------------------------------------------------------------------ clean: rm -rf target $(KERNEL_BIN) ##------------------------------------------------------------------------------ ## Run readelf ##------------------------------------------------------------------------------ readelf: $(KERNEL_ELF) $(call color_header, "Launching readelf") @$(DOCKER_TOOLS) $(READELF_BINARY) --headers $(KERNEL_ELF) ##------------------------------------------------------------------------------ ## Run objdump ##------------------------------------------------------------------------------ objdump: $(KERNEL_ELF) $(call color_header, "Launching objdump") @$(DOCKER_TOOLS) $(OBJDUMP_BINARY) --disassemble --demangle \ --section .text \ --section .rodata \ $(KERNEL_ELF) | rustfilt ##------------------------------------------------------------------------------ ## Run nm ##------------------------------------------------------------------------------ nm: $(KERNEL_ELF) $(call color_header, "Launching nm") @$(DOCKER_TOOLS) $(NM_BINARY) --demangle --print-size $(KERNEL_ELF) | sort | rustfilt ##-------------------------------------------------------------------------------------------------- ## Testing targets ##-------------------------------------------------------------------------------------------------- .PHONY: test test_boot ifeq ($(QEMU_MACHINE_TYPE),) # QEMU is not supported for the board. test_boot test: $(call color_header, "$(QEMU_MISSING_STRING)") else # QEMU is supported. ##------------------------------------------------------------------------------ ## Run boot test ##------------------------------------------------------------------------------ test_boot: $(KERNEL_BIN) $(call color_header, "Boot test - $(BSP)") @$(DOCKER_TEST) $(EXEC_TEST_DISPATCH) $(EXEC_QEMU) $(QEMU_RELEASE_ARGS) -kernel $(KERNEL_BIN) test: test_boot endif ================================================ FILE: X1_JTAG_boot/README.md ================================================ # Xtra 1 - JTAG boot Not much is happening here. The binary just patiently waits for a `JTAG` debugger to connect. ================================================ FILE: X1_JTAG_boot/build.rs ================================================ 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())); } ================================================ FILE: X1_JTAG_boot/src/_arch/aarch64/cpu/boot.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //! Architectural boot code. //! //! # Orientation //! //! Since arch modules are imported into generic modules using the path attribute, the path of this //! file is: //! //! crate::cpu::boot::arch_boot use core::arch::global_asm; // Assembly counterpart to this file. global_asm!( include_str!("boot.s"), CONST_CORE_ID_MASK = const 0b11 ); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- /// The Rust entry of the `kernel` binary. /// /// The function is called from the assembly `_start` function. #[no_mangle] pub unsafe fn _start_rust() -> ! { crate::kernel_init() } ================================================ FILE: X1_JTAG_boot/src/_arch/aarch64/cpu/boot.s ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2021-2023 Andre Richter //-------------------------------------------------------------------------------------------------- // Definitions //-------------------------------------------------------------------------------------------------- // Load the address of a symbol into a register, PC-relative. // // The symbol must lie within +/- 4 GiB of the Program Counter. // // # Resources // // - https://sourceware.org/binutils/docs-2.36/as/AArch64_002dRelocations.html .macro ADR_REL register, symbol adrp \register, \symbol add \register, \register, #:lo12:\symbol .endm //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- .section .text._start //------------------------------------------------------------------------------ // fn _start() //------------------------------------------------------------------------------ _start: // Only proceed on the boot core. Park it otherwise. mrs x1, MPIDR_EL1 and x1, x1, {CONST_CORE_ID_MASK} ldr x2, BOOT_CORE_ID // provided by bsp/__board_name__/cpu.rs cmp x1, x2 b.ne .L_parking_loop // If execution reaches here, it is the boot core. // Initialize DRAM. ADR_REL x0, __bss_start ADR_REL x1, __bss_end_exclusive .L_bss_init_loop: cmp x0, x1 b.eq .L_prepare_rust stp xzr, xzr, [x0], #16 b .L_bss_init_loop // Prepare the jump to Rust code. .L_prepare_rust: // Set the stack pointer. ADR_REL x0, __boot_core_stack_end_exclusive mov sp, x0 // Read the CPU's timer counter frequency and store it in ARCH_TIMER_COUNTER_FREQUENCY. // Abort if the frequency read back as 0. ADR_REL x1, ARCH_TIMER_COUNTER_FREQUENCY // provided by aarch64/time.rs mrs x2, CNTFRQ_EL0 cmp x2, xzr b.eq .L_parking_loop str w2, [x1] // Jump to Rust code. b _start_rust // Infinitely wait for events (aka "park the core"). .L_parking_loop: wfe b .L_parking_loop .size _start, . - _start .type _start, function .global _start ================================================ FILE: X1_JTAG_boot/src/_arch/aarch64/cpu.rs ================================================ // 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() } } ================================================ FILE: X1_JTAG_boot/src/_arch/aarch64/time.rs ================================================ // 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 #[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 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. #[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 {} } ================================================ FILE: X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_gpio.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! GPIO Driver. use crate::{ bsp::device_driver::common::MMIODerefWrapper, driver, synchronization, synchronization::NullLock, }; use tock_registers::{ interfaces::{ReadWriteable, Writeable}, register_bitfields, register_structs, registers::ReadWrite, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // GPIO registers. // // Descriptions taken from // - https://github.com/raspberrypi/documentation/files/1888662/BCM2837-ARM-Peripherals.-.Revised.-.V2-1.pdf // - https://datasheets.raspberrypi.org/bcm2711/bcm2711-peripherals.pdf register_bitfields! { u32, /// GPIO Function Select 1 GPFSEL1 [ /// Pin 15 FSEL15 OFFSET(15) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART RX ], /// Pin 14 FSEL14 OFFSET(12) NUMBITS(3) [ Input = 0b000, Output = 0b001, AltFunc0 = 0b100 // PL011 UART TX ] ], /// GPIO Pull-up/down Register /// /// BCM2837 only. GPPUD [ /// Controls the actuation of the internal pull-up/down control line to ALL the GPIO pins. PUD OFFSET(0) NUMBITS(2) [ Off = 0b00, PullDown = 0b01, PullUp = 0b10 ] ], /// GPIO Pull-up/down Clock Register 0 /// /// BCM2837 only. GPPUDCLK0 [ /// Pin 15 PUDCLK15 OFFSET(15) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ], /// Pin 14 PUDCLK14 OFFSET(14) NUMBITS(1) [ NoEffect = 0, AssertClock = 1 ] ], /// GPIO Pull-up / Pull-down Register 0 /// /// BCM2711 only. GPIO_PUP_PDN_CNTRL_REG0 [ /// Pin 15 GPIO_PUP_PDN_CNTRL15 OFFSET(30) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ], /// Pin 14 GPIO_PUP_PDN_CNTRL14 OFFSET(28) NUMBITS(2) [ NoResistor = 0b00, PullUp = 0b01 ] ] } register_structs! { #[allow(non_snake_case)] RegisterBlock { (0x00 => _reserved1), (0x04 => GPFSEL1: ReadWrite), (0x08 => _reserved2), (0x94 => GPPUD: ReadWrite), (0x98 => GPPUDCLK0: ReadWrite), (0x9C => _reserved3), (0xE4 => GPIO_PUP_PDN_CNTRL_REG0: ReadWrite), (0xE8 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; struct GPIOInner { registers: Registers, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the GPIO HW. pub struct GPIO { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl GPIOInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), } } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] fn disable_pud_14_15_bcm2837(&mut self) { use crate::time; use core::time::Duration; // The Linux 2837 GPIO driver waits 1 µs between the steps. const DELAY: Duration = Duration::from_micros(1); self.registers.GPPUD.write(GPPUD::PUD::Off); time::time_manager().spin_for(DELAY); self.registers .GPPUDCLK0 .write(GPPUDCLK0::PUDCLK15::AssertClock + GPPUDCLK0::PUDCLK14::AssertClock); time::time_manager().spin_for(DELAY); self.registers.GPPUD.write(GPPUD::PUD::Off); self.registers.GPPUDCLK0.set(0); } /// Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi4")] fn disable_pud_14_15_bcm2711(&mut self) { self.registers.GPIO_PUP_PDN_CNTRL_REG0.write( GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL15::PullUp + GPIO_PUP_PDN_CNTRL_REG0::GPIO_PUP_PDN_CNTRL14::PullUp, ); } /// Map PL011 UART as standard output. /// /// TX to pin 14 /// RX to pin 15 pub fn map_pl011_uart(&mut self) { // Select the UART on pins 14 and 15. self.registers .GPFSEL1 .modify(GPFSEL1::FSEL15::AltFunc0 + GPFSEL1::FSEL14::AltFunc0); // Disable pull-up/down on pins 14 and 15. #[cfg(feature = "bsp_rpi3")] self.disable_pud_14_15_bcm2837(); #[cfg(feature = "bsp_rpi4")] self.disable_pud_14_15_bcm2711(); } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl GPIO { pub const COMPATIBLE: &'static str = "BCM GPIO"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(GPIOInner::new(mmio_start_addr)), } } /// Concurrency safe version of `GPIOInner.map_pl011_uart()` pub fn map_pl011_uart(&self) { self.inner.lock(|inner| inner.map_pl011_uart()) } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for GPIO { fn compatible(&self) -> &'static str { Self::COMPATIBLE } } ================================================ FILE: X1_JTAG_boot/src/bsp/device_driver/bcm/bcm2xxx_pl011_uart.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! PL011 UART driver. //! //! # Resources //! //! - //! - use crate::{ bsp::device_driver::common::MMIODerefWrapper, console, cpu, driver, synchronization, synchronization::NullLock, }; use core::fmt; use tock_registers::{ interfaces::{Readable, Writeable}, register_bitfields, register_structs, registers::{ReadOnly, ReadWrite, WriteOnly}, }; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- // PL011 UART registers. // // Descriptions taken from "PrimeCell UART (PL011) Technical Reference Manual" r1p5. register_bitfields! { u32, /// Flag Register. FR [ /// Transmit FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// Line Control Register, LCR_H. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is empty. /// - If the FIFO is enabled, the TXFE bit is set when the transmit FIFO is empty. /// - This bit does not indicate if there is data in the transmit shift register. TXFE OFFSET(7) NUMBITS(1) [], /// Transmit FIFO full. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the transmit holding register is full. /// - If the FIFO is enabled, the TXFF bit is set when the transmit FIFO is full. TXFF OFFSET(5) NUMBITS(1) [], /// Receive FIFO empty. The meaning of this bit depends on the state of the FEN bit in the /// LCR_H Register. /// /// - If the FIFO is disabled, this bit is set when the receive holding register is empty. /// - If the FIFO is enabled, the RXFE bit is set when the receive FIFO is empty. RXFE OFFSET(4) NUMBITS(1) [], /// UART busy. If this bit is set to 1, the UART is busy transmitting data. This bit remains /// set until the complete byte, including all the stop bits, has been sent from the shift /// register. /// /// This bit is set as soon as the transmit FIFO becomes non-empty, regardless of whether /// the UART is enabled or not. BUSY OFFSET(3) NUMBITS(1) [] ], /// Integer Baud Rate Divisor. IBRD [ /// The integer baud rate divisor. BAUD_DIVINT OFFSET(0) NUMBITS(16) [] ], /// Fractional Baud Rate Divisor. FBRD [ /// The fractional baud rate divisor. BAUD_DIVFRAC OFFSET(0) NUMBITS(6) [] ], /// Line Control Register. LCR_H [ /// Word length. These bits indicate the number of data bits transmitted or received in a /// frame. #[allow(clippy::enum_variant_names)] WLEN OFFSET(5) NUMBITS(2) [ FiveBit = 0b00, SixBit = 0b01, SevenBit = 0b10, EightBit = 0b11 ], /// Enable FIFOs: /// /// 0 = FIFOs are disabled (character mode) that is, the FIFOs become 1-byte-deep holding /// registers. /// /// 1 = Transmit and receive FIFO buffers are enabled (FIFO mode). FEN OFFSET(4) NUMBITS(1) [ FifosDisabled = 0, FifosEnabled = 1 ] ], /// Control Register. CR [ /// Receive enable. If this bit is set to 1, the receive section of the UART is enabled. /// Data reception occurs for either UART signals or SIR signals depending on the setting of /// the SIREN bit. When the UART is disabled in the middle of reception, it completes the /// current character before stopping. RXE OFFSET(9) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// Transmit enable. If this bit is set to 1, the transmit section of the UART is enabled. /// Data transmission occurs for either UART signals, or SIR signals depending on the /// setting of the SIREN bit. When the UART is disabled in the middle of transmission, it /// completes the current character before stopping. TXE OFFSET(8) NUMBITS(1) [ Disabled = 0, Enabled = 1 ], /// UART enable: /// /// 0 = UART is disabled. If the UART is disabled in the middle of transmission or /// reception, it completes the current character before stopping. /// /// 1 = The UART is enabled. Data transmission and reception occurs for either UART signals /// or SIR signals depending on the setting of the SIREN bit UARTEN OFFSET(0) NUMBITS(1) [ /// If the UART is disabled in the middle of transmission or reception, it completes the /// current character before stopping. Disabled = 0, Enabled = 1 ] ], /// Interrupt Clear Register. ICR [ /// Meta field for all pending interrupts. ALL OFFSET(0) NUMBITS(11) [] ] } register_structs! { #[allow(non_snake_case)] pub RegisterBlock { (0x00 => DR: ReadWrite), (0x04 => _reserved1), (0x18 => FR: ReadOnly), (0x1c => _reserved2), (0x24 => IBRD: WriteOnly), (0x28 => FBRD: WriteOnly), (0x2c => LCR_H: WriteOnly), (0x30 => CR: WriteOnly), (0x34 => _reserved3), (0x44 => ICR: WriteOnly), (0x48 => @END), } } /// Abstraction for the associated MMIO registers. type Registers = MMIODerefWrapper; #[derive(PartialEq)] enum BlockingMode { Blocking, NonBlocking, } struct PL011UartInner { registers: Registers, chars_written: usize, chars_read: usize, } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Representation of the UART. pub struct PL011Uart { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl PL011UartInner { /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { registers: Registers::new(mmio_start_addr), chars_written: 0, chars_read: 0, } } /// Set up baud rate and characteristics. /// /// This results in 8N1 and 921_600 baud. /// /// The calculation for the BRD is (we set the clock to 48 MHz in config.txt): /// `(48_000_000 / 16) / 921_600 = 3.2552083`. /// /// This means the integer part is `3` and goes into the `IBRD`. /// The fractional part is `0.2552083`. /// /// `FBRD` calculation according to the PL011 Technical Reference Manual: /// `INTEGER((0.2552083 * 64) + 0.5) = 16`. /// /// Therefore, the generated baud rate divider is: `3 + 16/64 = 3.25`. Which results in a /// genrated baud rate of `48_000_000 / (16 * 3.25) = 923_077`. /// /// Error = `((923_077 - 921_600) / 921_600) * 100 = 0.16%`. pub fn init(&mut self) { // Execution can arrive here while there are still characters queued in the TX FIFO and // actively being sent out by the UART hardware. If the UART is turned off in this case, // those queued characters would be lost. // // For example, this can happen during runtime on a call to panic!(), because panic!() // initializes its own UART instance and calls init(). // // Hence, flush first to ensure all pending characters are transmitted. self.flush(); // Turn the UART off temporarily. self.registers.CR.set(0); // Clear all pending interrupts. self.registers.ICR.write(ICR::ALL::CLEAR); // From the PL011 Technical Reference Manual: // // The LCR_H, IBRD, and FBRD registers form the single 30-bit wide LCR Register that is // updated on a single write strobe generated by a LCR_H write. So, to internally update the // contents of IBRD or FBRD, a LCR_H write must always be performed at the end. // // Set the baud rate, 8N1 and FIFO enabled. self.registers.IBRD.write(IBRD::BAUD_DIVINT.val(3)); self.registers.FBRD.write(FBRD::BAUD_DIVFRAC.val(16)); self.registers .LCR_H .write(LCR_H::WLEN::EightBit + LCR_H::FEN::FifosEnabled); // Turn the UART on. self.registers .CR .write(CR::UARTEN::Enabled + CR::TXE::Enabled + CR::RXE::Enabled); } /// Send a character. fn write_char(&mut self, c: char) { // Spin while TX FIFO full is set, waiting for an empty slot. while self.registers.FR.matches_all(FR::TXFF::SET) { cpu::nop(); } // Write the character to the buffer. self.registers.DR.set(c as u32); self.chars_written += 1; } /// Block execution until the last buffered character has been physically put on the TX wire. fn flush(&self) { // Spin until the busy bit is cleared. while self.registers.FR.matches_all(FR::BUSY::SET) { cpu::nop(); } } /// Retrieve a character. fn read_char_converting(&mut self, blocking_mode: BlockingMode) -> Option { // If RX FIFO is empty, if self.registers.FR.matches_all(FR::RXFE::SET) { // immediately return in non-blocking mode. if blocking_mode == BlockingMode::NonBlocking { return None; } // Otherwise, wait until a char was received. while self.registers.FR.matches_all(FR::RXFE::SET) { cpu::nop(); } } // Read one character. let mut ret = self.registers.DR.get() as u8 as char; // Convert carrige return to newline. if ret == '\r' { ret = '\n' } // Update statistics. self.chars_read += 1; Some(ret) } } /// Implementing `core::fmt::Write` enables usage of the `format_args!` macros, which in turn are /// used to implement the `kernel`'s `print!` and `println!` macros. By implementing `write_str()`, /// we get `write_fmt()` automatically. /// /// The function takes an `&mut self`, so it must be implemented for the inner struct. /// /// See [`src/print.rs`]. /// /// [`src/print.rs`]: ../../print/index.html impl fmt::Write for PL011UartInner { fn write_str(&mut self, s: &str) -> fmt::Result { for c in s.chars() { self.write_char(c); } Ok(()) } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl PL011Uart { pub const COMPATIBLE: &'static str = "BCM PL011 UART"; /// Create an instance. /// /// # Safety /// /// - The user must ensure to provide a correct MMIO start address. pub const unsafe fn new(mmio_start_addr: usize) -> Self { Self { inner: NullLock::new(PL011UartInner::new(mmio_start_addr)), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ use synchronization::interface::Mutex; impl driver::interface::DeviceDriver for PL011Uart { fn compatible(&self) -> &'static str { Self::COMPATIBLE } unsafe fn init(&self) -> Result<(), &'static str> { self.inner.lock(|inner| inner.init()); Ok(()) } } impl console::interface::Write for PL011Uart { /// Passthrough of `args` to the `core::fmt::Write` implementation, but guarded by a Mutex to /// serialize access. fn write_char(&self, c: char) { self.inner.lock(|inner| inner.write_char(c)); } fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { // Fully qualified syntax for the call to `core::fmt::Write::write_fmt()` to increase // readability. self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) } fn flush(&self) { // Spin until TX FIFO empty is set. self.inner.lock(|inner| inner.flush()); } } impl console::interface::Read for PL011Uart { fn read_char(&self) -> char { self.inner .lock(|inner| inner.read_char_converting(BlockingMode::Blocking).unwrap()) } fn clear_rx(&self) { // Read from the RX FIFO until it is indicating empty. while self .inner .lock(|inner| inner.read_char_converting(BlockingMode::NonBlocking)) .is_some() {} } } impl console::interface::Statistics for PL011Uart { fn chars_written(&self) -> usize { self.inner.lock(|inner| inner.chars_written) } fn chars_read(&self) -> usize { self.inner.lock(|inner| inner.chars_read) } } impl console::interface::All for PL011Uart {} ================================================ FILE: X1_JTAG_boot/src/bsp/device_driver/bcm.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BCM driver top level. mod bcm2xxx_gpio; mod bcm2xxx_pl011_uart; pub use bcm2xxx_gpio::*; pub use bcm2xxx_pl011_uart::*; ================================================ FILE: X1_JTAG_boot/src/bsp/device_driver/common.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Common device driver code. use core::{marker::PhantomData, ops}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- pub struct MMIODerefWrapper { start_addr: usize, phantom: PhantomData T>, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl MMIODerefWrapper { /// Create an instance. pub const unsafe fn new(start_addr: usize) -> Self { Self { start_addr, phantom: PhantomData, } } } impl ops::Deref for MMIODerefWrapper { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*(self.start_addr as *const _) } } } ================================================ FILE: X1_JTAG_boot/src/bsp/device_driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Device driver. #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] mod bcm; mod common; #[cfg(any(feature = "bsp_rpi3", feature = "bsp_rpi4"))] pub use bcm::*; ================================================ FILE: X1_JTAG_boot/src/bsp/raspberrypi/cpu.rs ================================================ // 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; ================================================ FILE: X1_JTAG_boot/src/bsp/raspberrypi/driver.rs ================================================ // 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(()) } ================================================ FILE: X1_JTAG_boot/src/bsp/raspberrypi/kernel.ld ================================================ /* 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*) } } ================================================ FILE: X1_JTAG_boot/src/bsp/raspberrypi/memory.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! BSP Memory Management. //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// The board's physical memory map. #[rustfmt::skip] pub(super) mod map { pub const GPIO_OFFSET: usize = 0x0020_0000; pub const UART_OFFSET: usize = 0x0020_1000; /// Physical devices. #[cfg(feature = "bsp_rpi3")] pub mod mmio { use super::*; pub const START: usize = 0x3F00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } /// Physical devices. #[cfg(feature = "bsp_rpi4")] pub mod mmio { use super::*; pub const START: usize = 0xFE00_0000; pub const GPIO_START: usize = START + GPIO_OFFSET; pub const PL011_UART_START: usize = START + UART_OFFSET; } } ================================================ FILE: X1_JTAG_boot/src/bsp/raspberrypi.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Top-level BSP file for the Raspberry Pi 3 and 4. pub mod cpu; pub mod driver; pub mod memory; ================================================ FILE: X1_JTAG_boot/src/bsp.rs ================================================ // 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::*; ================================================ FILE: X1_JTAG_boot/src/console/null_console.rs ================================================ // 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 {} ================================================ FILE: X1_JTAG_boot/src/console.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! System console. mod null_console; use crate::synchronization::{self, NullLock}; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Console interfaces. pub mod interface { use core::fmt; /// Console write functions. pub trait Write { /// Write a single character. fn write_char(&self, c: char); /// Write a Rust format string. fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; /// Block until the last buffered character has been physically put on the TX wire. fn flush(&self); } /// Console read functions. pub trait Read { /// Read a single character. fn read_char(&self) -> char { ' ' } /// Clear RX buffers, if any. fn clear_rx(&self); } /// Console statistics. pub trait Statistics { /// Return the number of characters written. fn chars_written(&self) -> usize { 0 } /// Return the number of characters read. fn chars_read(&self) -> usize { 0 } } /// Trait alias for a full-fledged console. pub trait All: Write + Read + Statistics {} } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static CUR_CONSOLE: NullLock<&'static (dyn interface::All + Sync)> = NullLock::new(&null_console::NULL_CONSOLE); //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- use synchronization::interface::Mutex; /// Register a new console. pub fn register_console(new_console: &'static (dyn interface::All + Sync)) { CUR_CONSOLE.lock(|con| *con = new_console); } /// Return a reference to the currently registered console. /// /// This is the global console used by all printing macros. pub fn console() -> &'static dyn interface::All { CUR_CONSOLE.lock(|con| *con) } ================================================ FILE: X1_JTAG_boot/src/cpu/boot.rs ================================================ // 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; ================================================ FILE: X1_JTAG_boot/src/cpu.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Processor code. #[cfg(target_arch = "aarch64")] #[path = "_arch/aarch64/cpu.rs"] mod arch_cpu; mod boot; //-------------------------------------------------------------------------------------------------- // Architectural Public Reexports //-------------------------------------------------------------------------------------------------- pub use arch_cpu::{nop, wait_forever}; ================================================ FILE: X1_JTAG_boot/src/driver.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! Driver support. use crate::synchronization::{interface::Mutex, NullLock}; //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- const NUM_DRIVERS: usize = 5; struct DriverManagerInner { next_index: usize, descriptors: [Option; NUM_DRIVERS], } //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Driver interfaces. pub mod interface { /// Device Driver functions. pub trait DeviceDriver { /// Return a compatibility string for identifying the driver. fn compatible(&self) -> &'static str; /// Called by the kernel to bring up the device. /// /// # Safety /// /// - During init, drivers might do stuff with system-wide impact. unsafe fn init(&self) -> Result<(), &'static str> { Ok(()) } } } /// Tpye to be used as an optional callback after a driver's init() has run. pub type DeviceDriverPostInitCallback = unsafe fn() -> Result<(), &'static str>; /// A descriptor for device drivers. #[derive(Copy, Clone)] pub struct DeviceDriverDescriptor { device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, } /// Provides device driver management functions. pub struct DriverManager { inner: NullLock, } //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- static DRIVER_MANAGER: DriverManager = DriverManager::new(); //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- impl DriverManagerInner { /// Create an instance. pub const fn new() -> Self { Self { next_index: 0, descriptors: [None; NUM_DRIVERS], } } } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- impl DeviceDriverDescriptor { /// Create an instance. pub fn new( device_driver: &'static (dyn interface::DeviceDriver + Sync), post_init_callback: Option, ) -> Self { Self { device_driver, post_init_callback, } } } /// Return a reference to the global DriverManager. pub fn driver_manager() -> &'static DriverManager { &DRIVER_MANAGER } impl DriverManager { /// Create an instance. pub const fn new() -> Self { Self { inner: NullLock::new(DriverManagerInner::new()), } } /// Register a device driver with the kernel. pub fn register_driver(&self, descriptor: DeviceDriverDescriptor) { self.inner.lock(|inner| { inner.descriptors[inner.next_index] = Some(descriptor); inner.next_index += 1; }) } /// Helper for iterating over registered drivers. fn for_each_descriptor<'a>(&'a self, f: impl FnMut(&'a DeviceDriverDescriptor)) { self.inner.lock(|inner| { inner .descriptors .iter() .filter_map(|x| x.as_ref()) .for_each(f) }) } /// Fully initialize all drivers. /// /// # Safety /// /// - During init, drivers might do stuff with system-wide impact. pub unsafe fn init_drivers(&self) { self.for_each_descriptor(|descriptor| { // 1. Initialize driver. if let Err(x) = descriptor.device_driver.init() { panic!( "Error initializing driver: {}: {}", descriptor.device_driver.compatible(), x ); } // 2. Call corresponding post init callback. if let Some(callback) = &descriptor.post_init_callback { if let Err(x) = callback() { panic!( "Error during driver post-init callback: {}: {}", descriptor.device_driver.compatible(), x ); } } }); } } ================================================ FILE: X1_JTAG_boot/src/main.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter // Rust embedded logo for `make doc`. #![doc( html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" )] //! The `kernel` binary. //! //! # Code organization and architecture //! //! The code is divided into different *modules*, each representing a typical **subsystem** of the //! `kernel`. Top-level module files of subsystems reside directly in the `src` folder. For example, //! `src/memory.rs` contains code that is concerned with all things memory management. //! //! ## Visibility of processor architecture code //! //! Some of the `kernel`'s subsystems depend on low-level code that is specific to the target //! processor architecture. For each supported processor architecture, there exists a subfolder in //! `src/_arch`, for example, `src/_arch/aarch64`. //! //! The architecture folders mirror the subsystem modules laid out in `src`. For example, //! architectural code that belongs to the `kernel`'s MMU subsystem (`src/memory/mmu.rs`) would go //! into `src/_arch/aarch64/memory/mmu.rs`. The latter file is loaded as a module in //! `src/memory/mmu.rs` using the `path attribute`. Usually, the chosen module name is the generic //! module's name prefixed with `arch_`. //! //! For example, this is the top of `src/memory/mmu.rs`: //! //! ``` //! #[cfg(target_arch = "aarch64")] //! #[path = "../_arch/aarch64/memory/mmu.rs"] //! mod arch_mmu; //! ``` //! //! Often times, items from the `arch_ module` will be publicly reexported by the parent module. //! This way, each architecture specific module can provide its implementation of an item, while the //! caller must not be concerned which architecture has been conditionally compiled. //! //! ## BSP code //! //! `BSP` stands for Board Support Package. `BSP` code is organized under `src/bsp.rs` and contains //! target board specific definitions and functions. These are things such as the board's memory map //! or instances of drivers for devices that are featured on the respective board. //! //! Just like processor architecture code, the `BSP` code's module structure tries to mirror the //! `kernel`'s subsystem modules, but there is no reexporting this time. That means whatever is //! provided must be called starting from the `bsp` namespace, e.g. `bsp::driver::driver_manager()`. //! //! ## Kernel interfaces //! //! Both `arch` and `bsp` contain code that is conditionally compiled depending on the actual target //! and board for which the kernel is compiled. For example, the `interrupt controller` hardware of //! the `Raspberry Pi 3` and the `Raspberry Pi 4` is different, but we want the rest of the `kernel` //! code to play nicely with any of the two without much hassle. //! //! In order to provide a clean abstraction between `arch`, `bsp` and `generic kernel code`, //! `interface` traits are provided *whenever possible* and *where it makes sense*. They are defined //! in the respective subsystem module and help to enforce the idiom of *program to an interface, //! not an implementation*. For example, there will be a common IRQ handling interface which the two //! different interrupt controller `drivers` of both Raspberrys will implement, and only export the //! interface to the rest of the `kernel`. //! //! ``` //! +-------------------+ //! | Interface (Trait) | //! | | //! +--+-------------+--+ //! ^ ^ //! | | //! | | //! +----------+--+ +--+----------+ //! | kernel code | | bsp code | //! | | | arch code | //! +-------------+ +-------------+ //! ``` //! //! # Summary //! //! For a logical `kernel` subsystem, corresponding code can be distributed over several physical //! locations. Here is an example for the **memory** subsystem: //! //! - `src/memory.rs` and `src/memory/**/*` //! - Common code that is agnostic of target processor architecture and `BSP` characteristics. //! - Example: A function to zero a chunk of memory. //! - Interfaces for the memory subsystem that are implemented by `arch` or `BSP` code. //! - Example: An `MMU` interface that defines `MMU` function prototypes. //! - `src/bsp/__board_name__/memory.rs` and `src/bsp/__board_name__/memory/**/*` //! - `BSP` specific code. //! - Example: The board's memory map (physical addresses of DRAM and MMIO devices). //! - `src/_arch/__arch_name__/memory.rs` and `src/_arch/__arch_name__/memory/**/*` //! - Processor architecture specific code. //! - Example: Implementation of the `MMU` interface for the `__arch_name__` processor //! architecture. //! //! From a namespace perspective, **memory** subsystem code lives in: //! //! - `crate::memory::*` //! - `crate::bsp::memory::*` //! //! # Boot flow //! //! 1. The kernel's entry point is the function `cpu::boot::arch_boot::_start()`. //! - It is implemented in `src/_arch/__arch_name__/cpu/boot.s`. //! 2. Once finished with architectural setup, the arch code calls `kernel_init()`. #![allow(clippy::upper_case_acronyms)] #![feature(asm_const)] #![feature(const_option)] #![feature(format_args_nl)] #![feature(nonzero_min_max)] #![feature(panic_info_message)] #![feature(trait_alias)] #![feature(unchecked_math)] #![no_main] #![no_std] mod bsp; mod console; mod cpu; mod driver; mod panic_wait; mod print; mod synchronization; mod time; /// Early init code. /// /// # Safety /// /// - Only a single core must be active and running this function. /// - The init calls in this function must appear in the correct order. unsafe fn kernel_init() -> ! { // Initialize the BSP driver subsystem. if let Err(x) = bsp::driver::init() { panic!("Error initializing BSP driver subsystem: {}", x); } // Initialize all device drivers. driver::driver_manager().init_drivers(); // println! is usable from here on. // Transition from unsafe to safe. kernel_main() } /// The main function running after the early init. fn kernel_main() -> ! { info!("Parking CPU core. Please connect over JTAG now."); cpu::wait_forever() } ================================================ FILE: X1_JTAG_boot/src/panic_wait.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2018-2023 Andre Richter //! A panic handler that infinitely waits. use crate::{cpu, println}; use core::panic::PanicInfo; //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- /// Stop immediately if called a second time. /// /// # Note /// /// Using atomics here relieves us from needing to use `unsafe` for the static variable. /// /// On `AArch64`, which is the only implemented architecture at the time of writing this, /// [`AtomicBool::load`] and [`AtomicBool::store`] are lowered to ordinary load and store /// instructions. They are therefore safe to use even with MMU + caching deactivated. /// /// [`AtomicBool::load`]: core::sync::atomic::AtomicBool::load /// [`AtomicBool::store`]: core::sync::atomic::AtomicBool::store fn panic_prevent_reenter() { use core::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_arch = "aarch64"))] compile_error!("Add the target_arch to above's check if the following code is safe to use"); static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); return; } cpu::wait_forever() } #[panic_handler] fn panic(info: &PanicInfo) -> ! { // Protect against panic infinite loops if any of the following code panics itself. panic_prevent_reenter(); let timestamp = crate::time::time_manager().uptime(); let (location, line, column) = match info.location() { Some(loc) => (loc.file(), loc.line(), loc.column()), _ => ("???", 0, 0), }; println!( "[ {:>3}.{:06}] Kernel panic!\n\n\ Panic location:\n File '{}', line {}, column {}\n\n\ {}", timestamp.as_secs(), timestamp.subsec_micros(), location, line, column, info.message().unwrap_or(&format_args!("")), ); cpu::wait_forever() } ================================================ FILE: X1_JTAG_boot/src/print.rs ================================================ // 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)* )); }) } ================================================ FILE: X1_JTAG_boot/src/synchronization.rs ================================================ // SPDX-License-Identifier: MIT OR Apache-2.0 // // Copyright (c) 2020-2023 Andre Richter //! Synchronization primitives. //! //! # Resources //! //! - //! - //! - use core::cell::UnsafeCell; //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- /// Synchronization interfaces. pub mod interface { /// Any object implementing this trait guarantees exclusive access to the data wrapped within /// the Mutex for the duration of the provided closure. pub trait Mutex { /// The type of the data that is wrapped by this mutex. type Data; /// Locks the mutex and grants the closure temporary mutable access to the wrapped data. fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R; } } /// A pseudo-lock for teaching purposes. /// /// In contrast to a real Mutex implementation, does not protect against concurrent access from /// other cores to the contained data. This part is preserved for later lessons. /// /// The lock will only be used as long as it is safe to do so, i.e. as long as the kernel is /// executing single-threaded, aka only running on a single core with interrupts disabled. pub struct NullLock where T: ?Sized, { data: UnsafeCell, } //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- unsafe impl Send for NullLock where T: ?Sized + Send {} unsafe impl Sync for NullLock where T: ?Sized + Send {} impl NullLock { /// Create an instance. pub const fn new(data: T) -> Self { Self { data: UnsafeCell::new(data), } } } //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ impl interface::Mutex for NullLock { type Data = T; fn lock<'a, R>(&'a self, f: impl FnOnce(&'a mut Self::Data) -> R) -> R { // In a real lock, there would be code encapsulating this line that ensures that this // mutable reference will ever only be given out once at a time. let data = unsafe { &mut *self.data.get() }; f(data) } } ================================================ FILE: X1_JTAG_boot/src/time.rs ================================================ // 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 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. #[cfg(feature = "bsp_rpi3")] pub fn spin_for(&self, duration: Duration) { arch_time::spin_for(duration) } } ================================================ FILE: X1_JTAG_boot/tests/boot_test_string.rb ================================================ # frozen_string_literal: true EXPECTED_PRINT = 'Please connect over JTAG now' ================================================ FILE: X1_JTAG_boot/update.sh ================================================ #!/usr/bin/env bash BSP=rpi4 make cp kernel8.img jtag_boot_rpi4.img make cp kernel8.img jtag_boot_rpi3.img rm kernel8.img ================================================ FILE: common/docker.mk ================================================ DOCKER_IMAGE := rustembedded/osdev-utils:2021.12 ================================================ FILE: common/format.mk ================================================ define color_header @tput setaf 6 2> /dev/null || true @printf '\n%s\n' $(1) @tput sgr0 2> /dev/null || true endef define color_progress_prefix @tput setaf 2 2> /dev/null || true @tput bold 2 2> /dev/null || true @printf '%12s ' $(1) @tput sgr0 2> /dev/null || true endef ================================================ FILE: common/operating_system.mk ================================================ 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 ================================================ FILE: common/serial/minipush/progressbar_patch.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2020-2023 Andre Richter # Monkey-patch ruby-progressbar so that it supports reporting the progress in KiB instead of Byte. class ProgressBar # Add kibi version of progress class Progress def progress_kibi @progress / 1024 end end module Format # Add new formatting option class Molecule MOLECULES_EXTENDED = MOLECULES.dup MOLECULES_EXTENDED[:k] = %i[progressable progress_kibi] def initialize(letter) self.key = letter self.method_name = MOLECULES_EXTENDED.fetch(key.to_sym) end end end end ================================================ FILE: common/serial/minipush.rb ================================================ #!/usr/bin/env ruby # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2020-2023 Andre Richter require_relative 'miniterm' require 'ruby-progressbar' require_relative 'minipush/progressbar_patch' require 'timeout' class ProtocolError < StandardError; end # The main class class MiniPush < MiniTerm def initialize(serial_name, payload_path) super(serial_name) @name_short = 'MP' # override @payload_path = payload_path @payload_size = nil @payload_data = nil end private # The three characters signaling the request token form the consecutive sequence "\x03\x03\x03". def wait_for_payload_request puts "[#{@name_short}] 🔌 Please power the target now" # Timeout for the request token starts after the first sign of life was received. received = @target_serial.readpartial(4096) Timeout.timeout(10) do count = 0 loop do raise ProtocolError if received.nil? received.chars.each do |c| if c == "\u{3}" count += 1 return true if count == 3 else # A normal character resets token counting. count = 0 print c end end received = @target_serial.readpartial(4096) end end end def load_payload @payload_size = File.size(@payload_path) @payload_data = File.binread(@payload_path) end def send_size @target_serial.print([@payload_size].pack('L<')) raise ProtocolError if @target_serial.read(2) != 'OK' end def send_payload pb = ProgressBar.create( total: @payload_size, format: "[#{@name_short}] ⏩ Pushing %k KiB %b🦀%i %p%% %r KiB/s %a", rate_scale: ->(rate) { rate / 1024 }, length: 92, output: $stdout ) # Send in 512 byte chunks. while pb.progress < pb.total part = @payload_data.slice(pb.progress, 512) pb.progress += @target_serial.write(part) end end # override def handle_reconnect(_error) connection_reset puts puts "[#{@name_short}] ⚡ " \ "#{'Connection or protocol Error: '.light_red}" \ "#{'Remove power and USB serial. Reinsert serial first, then power'.light_red}" sleep(1) while serial_connected? end public # override def run open_serial wait_for_payload_request load_payload send_size send_payload terminal rescue ConnectionError, EOFError, Errno::EIO, ProtocolError, Timeout::Error => e handle_reconnect(e) retry rescue StandardError => e handle_unexpected(e) ensure connection_reset puts puts "[#{@name_short}] Bye 👋" end end ## ------------------------------------------------------------------------------------------------- ## Execution starts here ## ------------------------------------------------------------------------------------------------- if __FILE__ == $PROGRAM_NAME puts puts 'Minipush 1.0'.cyan puts # CTRL + C handler. Only here to suppress Ruby's default exception print. trap('INT') do # The `ensure` block from `MiniPush::run` will run after exit, restoring console state. exit end MiniPush.new(ARGV[0], ARGV[1]).run end ================================================ FILE: common/serial/miniterm.rb ================================================ #!/usr/bin/env ruby # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2020-2023 Andre Richter require 'rubygems' require 'bundler/setup' require 'colorize' require 'io/console' require 'serialport' SERIAL_BAUD = 921_600 class ConnectionError < StandardError; end # The main class class MiniTerm def initialize(serial_name) @name_short = 'MT' @target_serial_name = serial_name @target_serial = nil @host_console = IO.console end private def serial_connected? File.exist?(@target_serial_name) end def wait_for_serial return if serial_connected? puts "[#{@name_short}] ⏳ Waiting for #{@target_serial_name}" loop do sleep(1) break if serial_connected? end end def open_serial wait_for_serial @target_serial = SerialPort.new(@target_serial_name, SERIAL_BAUD, 8, 1, SerialPort::NONE) # Ensure all output is immediately flushed to the device. @target_serial.sync = true rescue Errno::EACCES => e puts "[#{@name_short}] 🚫 #{e.message} - Maybe try with 'sudo'" exit else puts "[#{@name_short}] ✅ Serial connected" end def terminal @host_console.raw! Thread.abort_on_exception = true Thread.report_on_exception = false # Receive from target and print on host console. target_to_host = Thread.new do loop do char = @target_serial.getc raise ConnectionError if char.nil? # Translate incoming newline to newline + carriage return. @host_console.putc("\r") if char == "\n" @host_console.putc(char) end end # Transmit host console input to target. loop do c = @host_console.getc # CTRL + C in raw mode was pressed. if c == "\u{3}" target_to_host.kill break end @target_serial.putc(c) end end def connection_reset @target_serial&.close @target_serial = nil @host_console.cooked! end # When the serial lost power or was removed during R/W operation. def handle_reconnect(_error) connection_reset puts puts "[#{@name_short}] ⚡ #{'Connection Error: Reinsert the USB serial again'.light_red}" end def handle_unexpected(error) connection_reset puts puts "[#{@name_short}] ⚡ #{"Unexpected Error: #{error.inspect}".light_red}" end public def run open_serial terminal rescue ConnectionError, EOFError, Errno::EIO => e handle_reconnect(e) retry rescue StandardError => e handle_unexpected(e) ensure connection_reset puts puts "[#{@name_short}] Bye 👋" end end ## ------------------------------------------------------------------------------------------------- ## Execution starts here ## ------------------------------------------------------------------------------------------------- if __FILE__ == $PROGRAM_NAME puts puts 'Miniterm 1.0'.cyan puts # CTRL + C handler. Only here to suppress Ruby's default exception print. trap('INT') do # The `ensure` block from `MiniTerm::run` will run after exit, restoring console state. exit end MiniTerm.new(ARGV[0]).run end ================================================ FILE: common/tests/boot_test.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter require_relative 'console_io_test' # Wait for an expected print during boot. class ExpectedBootPrintTest < SubtestBase def initialize(expected_print) super() @expected_print = expected_print end def name "Checking for the string: '#{@expected_print}'" end def run(qemu_out, _qemu_in) expect_or_raise(qemu_out, @expected_print) end end # Check for an expected string when booting the kernel in QEMU. class BootTest < ConsoleIOTest def initialize(qemu_cmd, expected_print) subtests = [ExpectedBootPrintTest.new(expected_print)] super(qemu_cmd, 'Boot test', subtests) end end ================================================ FILE: common/tests/console_io_test.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2019-2023 Andre Richter require 'expect' require 'pty' require 'timeout' require_relative 'test' # Error class for when expect times out. class ExpectTimeoutError < StandardError def initialize(string) super("Timeout while expecting string: #{string}") end end # Provide boilderplate for expecting a string and throwing an error on failure. class SubtestBase TIMEOUT_SECONDS = 3 def expect_or_raise(io, string, timeout = TIMEOUT_SECONDS) raise ExpectTimeoutError, string if io.expect(string, timeout).nil? end end # Monkey-patch IO so that we get access to the buffer of a previously unsuccessful expect(). class IO def unused_buf @unusedBuf end end # A wrapper class that records characters that have been received from a PTY. class PTYLoggerWrapper def initialize(pty, linebreak = "\n") @pty = pty @linebreak = linebreak @log = [] end def expect(pattern, timeout) result = @pty.expect(pattern, timeout) @log << if result.nil? @pty.unused_buf else result end result end def log @log.join.split(@linebreak) end end # A test doing console I/O with the QEMU binary. class ConsoleIOTest < Test MAX_TIME_ALL_TESTS_SECONDS = 20 def initialize(qemu_cmd, test_name, console_subtests) super() @qemu_cmd = qemu_cmd @console_subtests = console_subtests @test_name = test_name @test_description = "Running #{@console_subtests.length} console I/O tests" @test_output = [] @test_error = nil end private def format_test_name(number, name) formatted_name = "#{number.to_s.rjust(3)}. #{name}" formatted_name.ljust(63, '.') end def run_subtest(subtest, test_id, qemu_out, qemu_in) @test_output << format_test_name(test_id, subtest.name) subtest.run(qemu_out, qemu_in) @test_output.last.concat('[ok]') end # override def setup qemu_out, @qemu_in = PTY.spawn(@qemu_cmd) @qemu_out_wrapped = PTYLoggerWrapper.new(qemu_out) end # override def finish @test_output << '' @test_output << 'Console log:' @test_output += @qemu_out_wrapped.log.map { |line| " #{line}" } end # override def run_concrete_test @test_error = false Timeout.timeout(MAX_TIME_ALL_TESTS_SECONDS) do @console_subtests.each_with_index do |t, i| run_subtest(t, i + 1, @qemu_out_wrapped, @qemu_in) end end rescue Errno::EIO => e @test_error = "#{e.inspect} - QEMU might have quit early" rescue Timeout::Error @test_error = "Overall time for tests exceeded (#{MAX_TIME_ALL_TESTS_SECONDS}s)" rescue StandardError => e @test_error = e.inspect end end ================================================ FILE: common/tests/dispatch.rb ================================================ #!/usr/bin/env ruby # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2019-2023 Andre Richter file_dir = File.dirname(__FILE__) $LOAD_PATH.unshift(file_dir) unless $LOAD_PATH.include?(file_dir) require 'boot_test' require 'console_io_test' require 'exit_code_test' qemu_cmd = ARGV.join(' ') binary = ARGV.last test_name = binary.gsub(%r{.*deps/}, '').split('-')[0] # Check if virtual manifest (tutorial 12 or later) or not path_prefix = File.exist?('kernel/Cargo.toml') ? 'kernel/' : '' case test_name when 'kernel8.img' load "#{path_prefix}tests/boot_test_string.rb" # provides 'EXPECTED_PRINT' BootTest.new(qemu_cmd, EXPECTED_PRINT).run # Doesn't return when 'libkernel' ExitCodeTest.new(qemu_cmd, 'Kernel library unit tests').run # Doesn't return else console_test_file = "#{path_prefix}tests/#{test_name}.rb" test_name.concat('.rs') test = if File.exist?(console_test_file) load console_test_file # provides 'subtest_collection' ConsoleIOTest.new(qemu_cmd, test_name, subtest_collection) else ExitCodeTest.new(qemu_cmd, test_name) end test.run # Doesn't return end ================================================ FILE: common/tests/exit_code_test.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2019-2023 Andre Richter require 'English' require_relative 'test' require 'io/wait' # A test that only inspects the exit code of the QEMU binary. class ExitCodeTest < Test MAX_WAIT_SECS = 5 def initialize(qemu_cmd, test_name) super() @qemu_cmd = qemu_cmd @test_name = test_name @test_description = nil @test_output = [] @test_error = nil end private # override def setup @qemu_serial = IO.popen(@qemu_cmd) end # override # Convert the recorded output to an array of lines, and extract the test description. def finish @test_output = @test_output.join.split("\n") @test_description = @test_output.shift end # override def run_concrete_test Timeout.timeout(MAX_WAIT_SECS) do @test_output << @qemu_serial.read_nonblock(1024) while @qemu_serial.wait_readable end rescue EOFError @qemu_serial.close @test_error = $CHILD_STATUS.to_i.zero? ? false : 'QEMU exit status != 0' rescue Timeout::Error @test_error = 'Timed out waiting for test' rescue StandardError => e @test_error = e.inspect end end ================================================ FILE: common/tests/test.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2019-2023 Andre Richter # Test base class. class Test INDENT = ' ' def initialize # Template instance variables. # @test_name # @test_description # @test_output # @test_error end private def print_border(content) puts "#{INDENT}-------------------------------------------------------------------" puts content puts "#{INDENT}-------------------------------------------------------------------" end def print_header print_border("#{INDENT}🦀 #{@test_description}") puts end def print_footer_error(error) puts print_border("#{INDENT}❌ Failure: #{@test_name}: #{error}") puts puts end def print_footer_success puts print_border("#{INDENT}✅ Success: #{@test_name}") puts puts end # Expects @test_output the be an array of lines, without '\n' def print_output @test_output.each { |x| print "#{INDENT}#{x}\n" } end # Template method. def setup; end # Template method. def finish; end # Template method. def run_concrete_test raise('Not implemented') end public def run setup run_concrete_test finish print_header print_output exit_code = if @test_error print_footer_error(@test_error) false else print_footer_success true end exit(exit_code) end end ================================================ FILE: contributor_setup.sh ================================================ #!/usr/bin/env bash git config core.hooksPath .githooks # # Ruby and Bundler # if ! command -v bundle &> /dev/null then echo "'bundle' could not be found. Please install Ruby and Bundler." exit fi bundle config set --local path '.vendor/bundle' bundle install # # NPM # if ! command -v npm &> /dev/null then echo "'npm' could not be found. Please install it." exit fi npm install --save-dev --save-exact prettier # # Misspell # if ! command -v curl &> /dev/null then echo "'curl' could not be found. Please install it." exit fi curl -L -o ./install-misspell.sh https://raw.githubusercontent.com/client9/misspell/master/install-misspell.sh sh ./install-misspell.sh -b .vendor rm install-misspell.sh ================================================ FILE: devtool_completion.bash ================================================ #!/usr/bin/env bash complete -W "clean clippy copyright diff fmt fmt_check make make_xtra misspell ready_for_publish ready_for_publish_no_rust rubocop test test_boot test_integration test_unit test_xtra update" devtool ================================================ FILE: doc/14_BCM_driver.drawio ================================================ 7Vpbc+I2FP41zLSdCeM78Mgtu+k2TTakm+YpI2xhqxGWI4sA/fU9smXHNxqSjYFON8MQ6+j4WD7fuXyy6Zjj5eYTR1FwyTxMO4bmbTrmpGMYumUYHfnRvG0qsbSBmUp8Tjyl9SKYkb+xEmpKuiIejkuKgjEqSFQWuiwMsStKMsQ5W5fVFoyWrxohH9cEMxfRuvSOeCJIpYOi/DMmfqCu3NfUuufIffQ5W4Xqch3DXCR/6fQSZaaUfhwgj61LIrwR5ywU6gb+mK9CsQLxJQtZx54GQkgXDDvGOXwWUrHrM+ZTjCISd122BLEbg8r5Ai0JlQBkNkaJDbiIOe2YY86YSI+WmzGmEsAMmnQl5ztmcx9wHIp9Trh7+nX2rTd9ZtMvX26uru2/rsz1mbLyjOgKZ75KPCK2GQiJH7E0onXM0TogAs8i5MrZNcQdyAKxpDDS4VC64rx6x6nXzFEsOHvEY0YZh9mQhWBjVL+NbE2YC7wpiNRtfcJsiQXfgoqK6zPTyJBfF8NEyYJCiFi2EiKFrJ9be3EdHCjvNXtyZD/dTyYj3A8sfRyi4SSYfjuz9nAlxFkkD2UiYK7cNVPz0n0xOJaE/i2LpED6W6B5Fvq6o6eCPOYtpXHNYiIIC0FE8UJUICGUZj6HRMC6Z+NeDQ2YGTg9Ezmvgfg9eKlZ01SuyfHTnTp+ht2AXw70x+Nn1PDDGxdHqV+H8EHxNnQDDm5YxTVo4dYrfm+M9iIYSoQo8SVyLjg0CQrpSAJFcKgmlsTz5GUac6+cndV4ah1JS6siadeR1K1+E5JtAWm2nYjvzMOWsehXoDAGDUnVcxqSSu+1hoVVw2IeR2k6/fIjh3bg1pBCjtG1D5lDdkMOOVSiE5Uwc55Wkr+Mloj7JKmTUKGjDXwnztFS+ZlgUTpnFeYk3GcKOTmnwMttwpGv/idXJgUBWkrgaH10yxERuaisXrIGfiHVK8x5TZIJLm6+XqIQCCcvGJhX1UEWVWXvclhaPnKP7XJJfcFNKwi4XELG7jNb+m6z7SxZ6nLskxhQfghQCAnJf+p2uz833Y1UxiGaU1xSOZyDpW66yIcIhx40gwfCn+IjribiJBSNjiuvo1JVq6UwycW8Yqo+xUBrQZM9kCyvWRlMY0Y3XiuDhZJdLqb5zkoOYFtEXHVM0RzTUb5Pq9TztO7nxPcjmIptV5lKw57B0BqqrN5emXVOsMzmRW00vgT1C6nNVxEUVW0MMcAZpfJ0bcLJ89uroUeeG+8sc7hcofFvJQ+MJjZOI9ormysP4f7CbdpcOW4fzxcfxLrtXoUy9Ht2Qyw37X9bC+Xe66wbyuhQPhWC0Zwy91GGA4qDpFhIZ8L8eQJHUiFgVESkwqQLrh0OxtZ0JM/YEPGnPBu4Ujq6z2zB8WRTHGwLbG8n0AAR3xYsyuF9vlgYvNhMRpnRnRjHbMVdvEdFEJDQWOzB0LBXeoRWj5niPiwj/xxTJCB7S2trCgll7ppB5ynEnzPoVqqpYVX3EOmtqjOLj6Uqxiy9xn+re/zUGTVTSZzmd/odods/5Sp8jTmJAswRvRi/tdieBPE7k03k5usMLfDvK0p/k4lfoux3HLZkVyHd3mA/3knWD0K05FpvMPIKqzn49S9CAvtPJHDdU59T7ncrafE+jvof9kZHr/bGQSPPa+iNg9Z64+BNvdEjaMlC7zaQcVRoinqpKRpWvSnubmRZZyz2xbxLNnfGvPnl3a5wVjvNr79v83OO2Px6NfKVbS3e2vps81VTLbe+7EnToVjb60yrFGyv8az3EL5DhOcxuZlR52ZO9aXX3gGqGzVjh2ZndtN7tZNhZ9Cj/7PE7JbBzByIhObJpy6AQwhfq0g+pgl96ZWVYJwgeorkgskXNEIqmdqxuMbg9KiGXX+LeSSqob+HauSD/ahGJQjeX9qzIvODeRysrO/xlvawzKMUe20wjyNE6xGJiK7XiUjPfCcRMbVei0QEhi8/w0rVX35QZ07/AQ== ================================================ FILE: doc/14_GICv2_driver.drawio ================================================ 7VpbU+M2FP41mWk7k4zvIY9xLiy7pUsJ3YUnRrEVW0WxjKyQ0F9fyZYd2xIQsoSGtkwGpCP5SDrfdy5y6Nij5eaUgjQ+JyHEHcsINx173LEs07GsjvgY4WMhcQzHKSQRRaGctRXM0F9QCg0pXaEQZo2JjBDMUNoUBiRJYMAaMkApWTenLQhurpqCCCqCWQCwKv2OQhYX0kFd/gmiKJYrnxhy33MQ3EWUrBK5XMeyF/lPMbwEpSo5P4tBSNYNEdywKUmYPMAf81XCVlx8ThLScScxY8IEw4415Z+FmNiLCIkwBCnKegFZcnGQ8SnTBVgiLAAodfi5Dr6IPenYI0oIK1rLzQhiAWAJTbGT6ROjlQ0oTNguD3y//zz71p88kMmXL5dfL9w/v9rrrtTyAPAKlrbKLcIeSxByO0KhxOjY/jpGDM5SEIjRNecdl8VsiXnP5E1himn7xIXVbD9jlNzBEcGE8tGEJFyHrx6j3BOkDG5qInmsU0iWkNFHPkXyumtbJfLrOk2kLK5RxHGlEEhko0rb1nS8Ia2nt6Tv3t+Mxz48iR1zlIDhOJ586zo7mJLzLBVN4QiQSnPN5LgwX8YNi5LoiqRCIOzNwLykvumZhaDivCNnXJAMMUQSLsJwwVqQIIxLm3NHgGbowr6CBh8ZeH0beC+B+CN4yVHblqap8DM9FT/L1eBXAf32+FkKfnATwLSw65B/QPaYBDHlZlhlCrT86C27a9leB0OKAEaRQC7gBs1JIQyJeBAcyoElCkOxjNb3mt7Z5tPBkXSMNpKuiqTpnOiQPBSQrsYRPSzQSRuYefcrEXv9JaARyjHm7Eo3/HduHKOQd5lwRjHm1MYE3F2JnBiT4FU6eSuSf/OVUU0AlgI4rPauKECsEjWnN7Rxu6D2CnOqSErB2eXv5yDhyZLWFMzb07ksbcv2MlgRgiqLPWUSdcO6HcRUbKGsTEpd5tNqD7NlMZfCCGUc5dsYJNwh6U+9Xu9n3WnEZJiAOYaNKe9nYDG32ORtCpOQZ5RbRO+zf3A3KUUJ0xquuY9WVG2HwtwXq4gpcx3hsxY4r99EeC3DYMEZ03opDNZCdjOYVlWh6PCSDgWyjcEcYr+qMVvxvIj7VdJ+iyjruu0oq6l3LMNVo6z5FmH27Az6VhJ3N5/TeXT5EFy709kuleOPlTt7VjsvZzzF8Bp4nsTipJXwrIGmdOl7mtLF7B8KCrVymWdpUbP88u8pVN4YNk2d4lk9jQsdzIOcI6xTqqrg9Gw0fm21cBS5ussHeMEzAwv42wrjX0lw16yyZjFnTXgJo0xfXO1Wlxxq6z5I7qrdHV2CbN0lFwvoBYESQvhI2B/MDeNtfNcz+23n1aY/TcwdHMp3dXeMFjS88BqKd2C8FyKwJEl4FQtu+HxgmsOQm5T3JBKW84pUBjeIXctgKto3os3DV9Ebb2pD48eyk/CjX1fr8k7tKdHdPpb3yueKo8FQeVmn1DQZWdEAvhTzVKTrl8Uyd1KIAUMPzTV1QEp1F4SXmLWiqd9mzUlZRpVKit3K5+pvzlqqXPdFVYw7OGSKqpxb1Tn3p5t35Kli9GFTxf/xVom3g+MLt/1jCbfmPuG26rx7uPU+Yri13zPc6l8hvo5vcyyKTNsPQRbnNxyzQTujQbvc/1u0qznycDByJn49wVcsu6mTTMu45ylc0XHLwJt6MfAsHTXsK0B4zoyulsrvwkdHJVF/Tz46pnJ5bH8LceD0b6o3/OPK/w/WhywASt1ZCpLG/TFBbMYAg+rt8VPxCvNKvN198uV8Xd+u18r/YKGhCfQnO1Yae3yNy7vbL9sLz9z+24Q9+Rs= ================================================ FILE: doc/14_header.drawio ================================================ 7Vxbb+I4FP41SLsPrYhNAnlsaOlWmkpsO6OdeTSJE7wNcdaYFubXr50LIbEpKU2AtlRViU8SX875zh21A4ez5S1D8fSeejjsgK637MDrDgCGMTDFh6SsUkq/10sJASNe9lBBeCS/cUbsZtQF8fC89CCnNOQkLhNdGkXY5SUaYoy+lB/zaVheNUYBVgiPLgpV6j/E49OUaufbk/S/MAmm2cqDbnZjhvJnM8J8ijz6UiLhJR/RiGc7/DFZRHwhyPc0oh3zZsq5PONVB4zEry8fvAwoDUKMYjK/dOlMkN25eGTkoxkJJYPzOZxkDrEIvOnAIaOUp1ez5RCHUkA579OdjLbcXR+e4YjXeWFJLsZXt/BhzLybMf4ds8XPmwtop9M8o3CRcTVjCV/lbGZ0EXlYztLtQOdlSjh+jJEr774IYAnalM9CMTLEpeTFqHrklG3pzQxGhji/M+eMPuEhDSkTpIhG4o6TbQgzjpdbj2qsGSjQjekMc7YSj7xoYDDdgEDPyogoE2ywfrfgnLjImPcGRhoKH53HcXJhhVweNUZRia3WfwspeWeC3KcgYfGFmzJCoKrLgskfhiWEI/YrNtQ1bGt9DaD5Z/G+uArkJ4sJzBcTJ0jXS28lkH/CimAFg3lZelqB+CQMKyQUkiASQ1cIBAu6I8VFhGZeZTdmxPPkMlq4lAG1AQrQ3YWg94Aje6GXQWBVHm5AxzA10AFtIQfs1kAceVfSXhYC8NB8mnDQUNXvjczEnmJl36JnOl7lNIZDxMlzeXodA7MVxpSIhQtJmf2yqKoymNMFc3H21qbp2zVRZR6OWIC5Mk8izvWp95cwbN42ANMs7EG3sA2GaettQ+9sG+rYhsGJGQdLgc4DmscTzJJdj4n4I7FUlZ4IaGJ5OaPeItwUSoj9DHEuiYJvyShl7U6xcRprXHjbEqkIZKAKBPS1AmlLIn3VXA9B58oRMV8sFECcSgwdJ1e3CdNqtmTbxTzho1RpA8TLVF8rmrue5l2zOMN7cftOCpYtYmkYh+JNRsMQy+1dM2Gj2YaBmBTLV4C1YQ88RuPvieFUlXU3NDYNRwdAD+GB7ypWRtyx3AGe+M2AyTDKaDKABk7G4NJUAWW3hafBbvefa3MBMej8izlf5VnPICes051eI6q5XQG2s1hl6Cv28p0BwgUo+/V+eQLq+3PcikevkTXtyJOEFU9TYp8spbt7W+LUgC4Ao3cJzBL7QNdU3Z1GekZrSVR3N1/LAQJlfEoDGqHwG5X+KeFtogoZu9CC0zLn1WBaUEZE7vR6Z4xRFQReEv5TvihsRjr6lU0jr6+Xm4NVNujow26e29Kt3AFbZCz4kwTCr70L9WB4pwICw1ZA1K8XpDelioaaebeKmSkK/SFhbqgiR0iFrTbQIIe/ysMCEclotR7l5TVr7QNz4/7mqooek8bJYdI+GCSrBqttSNZJ6cOQxPNtWdC+BTU53oidusmPLrhXwqz1o5XAzE9+BD2W3Er4Zzod81rnwhgWsSiaJEcsQNW4l9IlZQf1Umo+/ym8f//Y3r+n8PUWR5gRV64WefIvc6fi4wmzKOlluNRTSxdtJL/rmsV7khxseCbu67TPtvoQWU0lOYpooanLczSyrfru5mSrFjK+TmS3V8Bm1/XAg0O5UVgtm7btRjWllnNk11Bkt38ScURMwnL5BlaLfG0Dskat5hzX7Rt/QOPYcd3nrOrA3pHjOqBm6HcPf9+jCAVJ+fk7Q4QrnD6dBtSbtPQxO4HRhDChmspCnTAP2q5Wk9uzNPeUJtQWXA8qTTWX/WINRtMqBxXH7zACNQ9uqsXYQH9RmeLqQTYXb++Gz3LTJ9BL9H1sudpeote3J92GIhjTLuPmFHqJuXn5OM3EFOtfvJsIahRHTj3wtOzTayeCAxcQPnzRKc+vdyb4oJ3ejWUfvZ0IauT456LTAYtOuXE8JUweuJ8IahQmznWnvd3UsfuJudX9bO7/2P1EqNadzv3EfRKdE+wnQrUKdQ7tXg3tzJpuFG7JyJp3o4fuJ8Ia39s4h3YHDO1qpxstYbJf+Tr4ofuJUFPoO8d1TcUfR+8nwhrVuA8Y1x29nwjVctm5A1VHmH3NV2OP3k+EapHuLM09pdlmP1EMi/9VkHrA4r9KwJv/AQ== ================================================ FILE: doc/demo_PS1.txt ================================================ export PS1="\[\033[01;32m\]rust@osdev\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\] >> " ================================================ FILE: doc/source_section_divider.txt ================================================ //-------------------------------------------------------------------------------------------------- // Private Definitions //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // Public Definitions //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // Global instances //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // Private Code //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // Public Code //-------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------ // OS Interface Code //------------------------------------------------------------------------------ //-------------------------------------------------------------------------------------------------- // Testing //-------------------------------------------------------------------------------------------------- ================================================ FILE: docker/README.md ================================================ # Docker containers for easy dependency bundling To facilitate downloading, building and running the required development tools, some of the tutorials in this repository use a container software called docker. While docker specifics are outside of this tutorial's scope it is worth mentioning that human readable docker configuration files named "Dockerfile" exist in the sub-directories of this folder. These files may be of interest to those who want details about what will happen when docker is invoked. ================================================ FILE: docker/rustembedded-osdev-utils/Dockerfile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2017-2023 Andre Richter ## Copyright (c) 2019-2023 Nao Taco FROM ubuntu:20.04 ARG VCS_REF ARG GCC_AARCH64=https://developer.arm.com/-/media/Files/downloads/gnu-a/10.3-2021.07/binrel/gcc-arm-10.3-2021.07-aarch64-aarch64-none-elf.tar.xz ARG GCC_X86_64=https://developer.arm.com/-/media/Files/downloads/gnu-a/10.3-2021.07/binrel/gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz LABEL org.label-schema.vcs-ref=$VCS_REF \ org.label-schema.vcs-url="https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials" LABEL maintainer="The resources team , Andre Richter " # Ruby gems COPY Gemfile . RUN set -ex; \ tempPkgs=' \ automake \ bison \ build-essential \ flex \ git \ libtool \ ninja-build \ pkg-config \ wget \ '; \ apt-get update; \ apt-get install -q -y --no-install-recommends \ $tempPkgs \ # persistent packages ca-certificates \ gdb-multiarch \ libpixman-1-dev \ libglib2.0-dev \ libusb-1.0.0-dev \ locales \ python3 \ ruby \ ruby-dev \ ; \ # GCC AArch64 tools if [ "$(uname -m)" = "aarch64" ]; then wget ${GCC_AARCH64}; else wget ${GCC_X86_64}; fi; \ tar -xf gcc-arm-10*; \ cp \ gcc-arm-10*/bin/aarch64-none-elf-objdump \ gcc-arm-10*/bin/aarch64-none-elf-readelf \ gcc-arm-10*/bin/aarch64-none-elf-nm \ /usr/local/bin/; \ rm -rf gcc-arm-10*; \ # Ruby dependencies gem install bundler; \ bundle config set --local without 'development'; \ bundle install --retry 3; \ # QEMU git clone https://gitlab.com/qemu-project/qemu.git; \ cd qemu; \ git checkout tags/v6.1.0; \ ./configure --target-list=aarch64-softmmu --enable-modules \ --enable-tcg-interpreter --enable-debug-tcg \ --python=/usr/bin/python3; \ make -j10; \ make install; \ cd ..; \ rm -rf qemu; \ # Openocd git clone --depth 1 https://git.code.sf.net/p/openocd/code openocd; \ cd openocd; \ ./bootstrap; \ ./configure --enable-ftdi; \ make -j10; \ make install; \ # GDB wget -P ~ git.io/.gdbinit; \ # Cleanup apt-get purge -y --auto-remove $tempPkgs; \ apt-get autoremove -q -y; \ apt-get clean -q -y; \ rm -rf /var/lib/apt/lists/* # Locales RUN locale-gen en_US.UTF-8 ENV LANG=en_US.UTF-8 \ LANGUAGE=en_US:en \ LC_ALL=en_US.UTF-8 \ RUBYOPT=-W0 # Openocd COPY rpi3.cfg /openocd/ COPY rpi4.cfg /openocd/ # GDB COPY auto /root/.gdbinit.d/auto ================================================ FILE: docker/rustembedded-osdev-utils/Makefile ================================================ ## SPDX-License-Identifier: MIT OR Apache-2.0 ## ## Copyright (c) 2019-2023 Andre Richter # Reference followed: https://www.docker.com/blog/getting-started-with-docker-for-arm-on-linux TAG := 2021.12 default: build_local build_local: cp ../../Gemfile . docker build \ --tag rustembedded/osdev-utils:$(TAG) \ --build-arg VCS_REF=`git rev-parse --short HEAD` . rm Gemfile buildx_push: cp ../../Gemfile . docker buildx build \ --push \ --platform linux/arm64/v8,linux/amd64 \ --tag rustembedded/osdev-utils:$(TAG) \ --build-arg VCS_REF=`git rev-parse --short HEAD` . rm Gemfile ================================================ FILE: docker/rustembedded-osdev-utils/auto ================================================ dashboard -layout assembly expressions history memory registers source stack ================================================ FILE: docker/rustembedded-osdev-utils/rpi3.cfg ================================================ # Script from # https://www.suse.com/c/debugging-raspberry-pi-3-with-jtag/ # with minor adaptions. transport select jtag # we need to enable srst even though we don't connect it reset_config trst_and_srst adapter_khz 1000 jtag_ntrst_delay 500 if { [info exists CHIPNAME] } { set _CHIPNAME $CHIPNAME } else { set _CHIPNAME rpi3 } # # Main DAP # if { [info exists DAP_TAPID] } { set _DAP_TAPID $DAP_TAPID } else { set _DAP_TAPID 0x4ba00477 } jtag newtap $_CHIPNAME tap -irlen 4 -ircapture 0x1 -irmask 0xf -expected-id $_DAP_TAPID -enable dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.tap set _TARGETNAME $_CHIPNAME.core set _CTINAME $_CHIPNAME.cti set DBGBASE {0x80010000 0x80012000 0x80014000 0x80016000} set CTIBASE {0x80018000 0x80019000 0x8001a000 0x8001b000} set _cores 4 for { set _core 0 } { $_core < $_cores } { incr _core } { cti create $_CTINAME.$_core -dap $_CHIPNAME.dap -ap-num 0 \ -ctibase [lindex $CTIBASE $_core] target create $_TARGETNAME$_core aarch64 \ -dap $_CHIPNAME.dap -coreid $_core \ -dbgbase [lindex $DBGBASE $_core] -cti $_CTINAME.$_core $_TARGETNAME$_core configure -event reset-assert-post "aarch64 dbginit" $_TARGETNAME$_core configure -event gdb-attach { halt } } ================================================ FILE: docker/rustembedded-osdev-utils/rpi4.cfg ================================================ # Script from # https://www.suse.com/c/debugging-raspberry-pi-3-with-jtag/ # with minor adaptions. transport select jtag # we need to enable srst even though we don't connect it reset_config trst_and_srst adapter_khz 1000 jtag_ntrst_delay 500 if { [info exists CHIPNAME] } { set _CHIPNAME $CHIPNAME } else { set _CHIPNAME rpi4 } # # Main DAP # if { [info exists DAP_TAPID] } { set _DAP_TAPID $DAP_TAPID } else { set _DAP_TAPID 0x4ba00477 } jtag newtap $_CHIPNAME tap -irlen 4 -ircapture 0x1 -irmask 0xf -expected-id $_DAP_TAPID -enable dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.tap set _TARGETNAME $_CHIPNAME.core set _CTINAME $_CHIPNAME.cti set DBGBASE {0x80410000 0x80510000 0x80610000 0x80710000} set CTIBASE {0x80420000 0x80520000 0x80620000 0x80720000} set _cores 4 for { set _core 0 } { $_core < $_cores } { incr _core } { cti create $_CTINAME.$_core -dap $_CHIPNAME.dap -ap-num 0 \ -ctibase [lindex $CTIBASE $_core] target create $_TARGETNAME$_core aarch64 \ -dap $_CHIPNAME.dap -coreid $_core \ -dbgbase [lindex $DBGBASE $_core] -cti $_CTINAME.$_core $_TARGETNAME$_core configure -event reset-assert-post "aarch64 dbginit" $_TARGETNAME$_core configure -event gdb-attach { halt } } ================================================ FILE: rust-toolchain.toml ================================================ [toolchain] channel = "nightly-2022-10-13" components = ["rust-src", "llvm-tools-preview", "rustfmt"] targets = ["aarch64-unknown-none-softfloat"] ================================================ FILE: utils/devtool/copyright.rb ================================================ # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2018-2023 Andre Richter require 'rubygems' require 'bundler/setup' require 'colorize' def copyright_check_files(source_files) source_files.sort.each do |f| puts 'Checking for copyright: '.light_blue + f.to_s years = copyright_years(f) unless years.include?(Time.now.year) puts "\tOnly found years: #{years}".red return false end end true end def copyright_years(file) years = [] File.readlines(file).grep(/.*Copyright.*/).each do |x| years << x.scan(/\d\d\d\d/).map!(&:to_i) end years.flatten end ================================================ FILE: utils/devtool.rb ================================================ #!/usr/bin/env ruby # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2020-2023 Andre Richter require 'rubygems' require 'bundler/setup' require 'colorize' require 'fileutils' require_relative 'devtool/copyright' # Actions for tutorial folders. class TutorialCrate attr_reader :folder def initialize(folder) @folder = folder end def tutorial? /[0-9]/.match?(@folder[0]) end def clean puts 'Cleaning '.light_blue + @folder # No output needed. Dir.chdir(@folder) { `make clean` } end def update puts "\n\n" puts 'Updating '.light_blue + @folder Dir.chdir(@folder) { system('cargo update') } end def clippy(bsp) puts "\n\n" puts "Clippy #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make clippy") } end def fmt_cargo_rust(args) Dir.chdir(@folder) { exit(1) unless system("cargo fmt #{args}") } end def make(bsp) puts "\n\n" puts "Make #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make") } end def test(bsp) return unless boot_test? puts "\n\n" puts "Test #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test") } end def test_boot(bsp) return unless boot_test? puts "\n\n" puts "Test Boot #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test_boot") } end def test_unit(bsp) return unless unit_integration_tests? puts "\n\n" puts "Test Unit #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test_unit") } end def test_integration(bsp) return unless unit_integration_tests? puts "\n\n" puts "Test Integration #{@folder} - BSP: #{bsp}".light_blue Dir.chdir(@folder) { exit(1) unless system("BSP=#{bsp} make test_integration") } end private def boot_test? Dir.exist?("#{@folder}/tests") || Dir.exist?("#{@folder}/kernel/tests") end def unit_integration_tests? !Dir.glob("#{@folder}/kernel/tests/00_*.rs").empty? end end # Forks commands to all applicable receivers. class DevTool def initialize @user_has_supplied_crates = false @bsp = bsp_from_env || SUPPORTED_BSPS.first cl = user_supplied_crate_list || Dir['*/Cargo.toml'] @crates = cl.map { |c| TutorialCrate.new(c.delete_suffix('/Cargo.toml')) } end def clean @crates.each(&:clean) end def update @crates.each(&:update) end def clippy(bsp = nil) bsp ||= @bsp @crates.each { |c| c.clippy(bsp) } end def diff tuts = tutorials.map(&:folder) padding = tuts.map(&:length).max tuts[0..-2].each_with_index do |original, i| update = tuts[i + 1] diff_pair(original, update, padding) end end def fmt fmt_cargo_rust(check: false) puts fmt_prettier(check: false) end def fmt_check fmt_cargo_rust(check: true) puts fmt_prettier(check: true) end def make(bsp = nil) bsp ||= @bsp @crates.each { |c| c.make(bsp) } end def make_xtra return if @user_has_supplied_crates puts "\n\n" puts 'Make Xtra stuff'.light_blue system('cd *_uart_chainloader && bash update.sh') system('cd X1_JTAG_boot && bash update.sh') end def test(bsp = nil) bsp ||= @bsp @crates.each { |c| c.test(bsp) } end def test_boot(bsp = nil) bsp ||= @bsp @crates.each { |c| c.test_boot(bsp) } end def test_unit(bsp = nil) bsp ||= @bsp @crates.each { |c| c.test_unit(bsp) } end def test_integration(bsp = nil) bsp ||= @bsp @crates.each { |c| c.test_integration(bsp) } end def copyright exit(1) unless copyright_check_files(copyright_source_files) end def misspell puts 'Misspell'.light_blue translations = ['README.CN.md', 'README.ES.md'] files = tracked_files.reject { |f| translations.include?(File.basename(f)) } files = files.join(' ') exit(1) unless system(".vendor/misspell -error #{files}") end def rubocop puts 'Rubocop'.light_blue exit(1) unless system('bundle exec rubocop') end def ready_for_publish_no_rust clean fmt rubocop copyright diff misspell clean end def ready_for_publish ready_for_publish_no_rust make_xtra clippy('rpi4') clippy('rpi3') test_boot('rpi3') test_unit('rpi3') test_integration('rpi3') clean end private SUPPORTED_BSPS = %w[rpi3 rpi4].freeze def bsp_from_env bsp = ENV.fetch('BSP', nil) return bsp if SUPPORTED_BSPS.include?(bsp) nil end def fmt_cargo_rust(check: false) args = '-- --check' if check @crates.each do |c| print 'Rust cargo fmt '.light_blue print "#{args} ".light_blue unless args.nil? puts c.folder Process.fork { c.fmt_cargo_rust(args) } end Process.waitall end def fmt_prettier(check: false) args = if check '--check' else '--write' end args += if @user_has_supplied_crates " #{@crates.map(&:folder).join(' ')}" else ' .' end puts 'Prettier:'.light_blue exit(1) unless system("./node_modules/.bin/prettier #{args}") end def user_supplied_crate_list folders = ARGV.drop(1) return nil if folders.empty? crates = folders.map { |d| "#{d}/Cargo.toml" }.sort crates.each do |c| unless File.exist?(c) puts "Crate not found: #{c}" exit(1) end end @user_has_supplied_crates = true crates end def tutorials @crates.select(&:tutorial?) end def tracked_files crate_list = @crates.map(&:folder).join(' ') if @user_has_supplied_crates `git ls-files #{crate_list}`.split("\n") # crates_list == nil means all files end def diff_pair(original, update, padding) # Only diff adjacent tutorials. This checks the numbers of the tutorial folders. return unless original[0..1].to_i + 1 == update[0..1].to_i # 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 def copyright_source_files extensions = ['.S', '.rs', '.rb'] # NOTE: The selection result is the return value of the function. tracked_files.select do |f| next unless File.exist?(f) next if f.include?('build.rs') next if f.include?('boot_test_string.rb') f.include?('Makefile') || f.include?('Dockerfile') || extensions.include?(File.extname(f)) end end end ## ------------------------------------------------------------------------------------------------- ## Execution starts here ## ------------------------------------------------------------------------------------------------- tool = DevTool.new cmd = ARGV[0] commands = tool.public_methods(false).sort if commands.include?(cmd&.to_sym) tool.public_send(cmd) else puts "Usage: ./#{__FILE__.split('/').last} COMMAND [optional list of folders]" puts puts 'Commands:' commands.each { |m| puts " #{m}" } exit(1) end ================================================ FILE: utils/diff_tut_folders.bash ================================================ #!/usr/bin/env bash # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2018-2023 Andre Richter DIFF=$( diff -uNr \ -x README.md \ -x README.CN.md \ -x README.ES.md \ -x kernel8.img \ -x Cargo.lock \ -x target \ $1 $2 \ | 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 kernel8.img -x Cargo.lock -x target/\ndiff -uNr/g" ) HEADER="## Diff to previous" ORIGINAL=$( cat $2/README.md \ | sed -rn "/$HEADER/q;p" ) echo "$ORIGINAL" > "$2/README.md" printf "\n$HEADER\n" >> "$2/README.md" printf "\`\`\`diff\n" >> "$2/README.md" echo "$DIFF" >> "$2/README.md" printf "\n\`\`\`\n" >> "$2/README.md" ================================================ FILE: utils/update_copyright.rb ================================================ #!/usr/bin/env ruby # frozen_string_literal: true # SPDX-License-Identifier: MIT OR Apache-2.0 # # Copyright (c) 2021-2023 Andre Richter require 'date' files = `git ls-files`.split("\n") files = files.delete_if { |f| File.symlink?(f) } files = files.join(' ') year = Date.today.year `sed -i -- 's,\\(Copyright .* 20..\\)-20..,\\1-#{year},g' #{files}` `sed -i -- 's,\\(Copyright .* #{year - 1}\\) ,\\1-#{year} ,g' #{files}`