├── .cargo └── config.toml ├── .github ├── actions │ └── setup-build-env │ │ └── action.yaml └── workflows │ ├── audit.yaml │ └── build.yaml ├── .gitignore ├── .gitmodules ├── COPYRIGHT ├── Cargo.lock ├── Cargo.toml ├── Makefile ├── README.md ├── biostation ├── COPYING ├── Cargo.toml ├── README.md ├── build.rs ├── kernel-linkfile.ld └── src │ ├── cache │ └── mod.rs │ ├── exceptions │ ├── common │ │ ├── handler.S │ │ ├── mod.rs │ │ └── syscall │ │ │ ├── handler.S │ │ │ └── mod.rs │ └── mod.rs │ ├── gs │ ├── imr.rs │ └── mod.rs │ ├── main.rs │ ├── romdir │ └── mod.rs │ └── thread │ ├── glue.S │ └── mod.rs ├── hello-rs ├── .cargo │ └── config.toml ├── .gitignore ├── Cargo.toml ├── ps2.json └── src │ └── main.rs ├── playstation2-pac-rs ├── Cargo.toml ├── README.md ├── rust-toolchain.toml └── src │ └── lib.rs ├── prussia_bios ├── Cargo.toml └── src │ └── lib.rs ├── prussia_debug ├── Cargo.toml ├── README.md └── src │ └── lib.rs ├── prussia_dma ├── Cargo.toml ├── README.md ├── ps2.json └── src │ ├── control.rs │ ├── devices │ ├── gif.rs │ ├── ipu.rs │ ├── mod.rs │ ├── sif.rs │ ├── spram.rs │ ├── traits.rs │ └── vif.rs │ └── lib.rs ├── prussia_intc ├── Cargo.toml └── src │ └── lib.rs ├── prussia_rt ├── .gitignore ├── Cargo.toml ├── README.md ├── build.rs ├── libprussia-rt.a ├── ps2.json ├── rebuild-asm-lib.sh ├── src │ ├── atomic.rs │ ├── cop0.rs │ ├── interrupts.rs │ ├── lib.rs │ └── routines.S └── user-linkfile.ld ├── ps2.json ├── ps2.xml └── rust-toolchain.toml /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | target = "./ps2.json" 3 | 4 | [unstable] 5 | build-std = ["core", "compiler_builtins"] 6 | build-std-features = ["compiler-builtins-mem"] 7 | -------------------------------------------------------------------------------- /.github/actions/setup-build-env/action.yaml: -------------------------------------------------------------------------------- 1 | name: Set up build environment 2 | description: Sets up GNU-binutils and Rust. 3 | 4 | inputs: 5 | binutils-version: 6 | description: A tag or branch specifying the version of binutils to install. 7 | default: binutils-2_44 8 | required: false 9 | rust-toolchain: 10 | description: The channel or version of the Rust toolchain to install. 11 | default: nightly 12 | required: false 13 | 14 | outputs: 15 | binutils-loc: 16 | description: Path to binutils. Must be added to GITHUB_PATH. 17 | value: ${{ steps.paths.outputs.binutils-loc }} 18 | cargo-loc: 19 | description: Path to Cargo and Rustup. Must be added to GITHUB_PATH. 20 | value: ${{ steps.paths.outputs.cargo-loc }} 21 | 22 | runs: 23 | using: composite 24 | steps: 25 | - name: Configure env and paths 26 | id: globals 27 | run: | 28 | echo "BINUTILS_LOC=/opt/binutils-mips" >> "${GITHUB_OUTPUT}" 29 | echo "CARGO_LOC=$HOME/.cargo" >> "${GITHUB_OUTPUT}" 30 | echo "RUSTUP_LOC=$HOME/.rustup" >> "${GITHUB_OUTPUT}" 31 | echo "TARGET=mips64el-none-elf" >> "${GITHUB_OUTPUT}" 32 | shell: bash 33 | 34 | - name: Cache gnu-binutils 35 | id: cache-binutils 36 | uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 37 | with: 38 | path: ${{ steps.globals.outputs.BINUTILS_LOC }} 39 | key: ${{ runner.os }}-build-${{ steps.globals.outputs.TARGET }}-${{ inputs.binutils-version }} 40 | 41 | - name: Cache Rust 42 | id: cache-rust 43 | uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 # v2.7.8 44 | 45 | - name: Setup gnu-binutils 46 | if: ${{ steps.cache-binutils.outputs.cache-hit != 'true' }} 47 | env: 48 | BINUTILS_VERSION: ${{ inputs.binutils-version }} 49 | BINUTILS_LOC: ${{ steps.globals.outputs.BINUTILS_LOC }} 50 | TARGET: ${{ steps.globals.outputs.TARGET }} 51 | run: | 52 | sudo apt update 53 | sudo apt install -y gcc clang make texinfo libmpc-dev bison flex 54 | git clone --branch "$BINUTILS_VERSION" https://sourceware.org/git/binutils-gdb.git 55 | cd binutils-gdb 56 | mkdir build 57 | cd build 58 | ../configure --target=$TARGET --prefix=$BINUTILS_LOC 59 | make configure-host 60 | make -j$(nproc) 61 | sudo make install 62 | shell: bash 63 | 64 | - name: Set up Rust toolchain 65 | if: ${{ steps.cache-rust.outputs.cache-hit != 'true' }} 66 | env: 67 | RUST_TOOLCHAIN: ${{ inputs.rust-toolchain }} 68 | run: | 69 | # Installs rustup if not found (usually the case when using gh act for local testing). 70 | if ! command -v echos >/dev/null 2>&1 >/dev/null 71 | then 72 | curl https://sh.rustup.rs -sSf | sh -s -- -y 73 | . "$HOME/.cargo/env" 74 | fi 75 | 76 | rustup update $RUST_TOOLCHAIN && rustup default $RUST_TOOLCHAIN 77 | shell: bash 78 | 79 | - name: Install dev tools 80 | if: ${{ steps.cache-rust.outputs.cache-hit != 'true' }} 81 | env: 82 | CARGO_BIN: ${{ steps.globals.outputs.CARGO_LOC }}/bin/cargo 83 | run: | 84 | $CARGO_BIN install cargo-audit 85 | shell: bash 86 | 87 | - name: Output paths 88 | id: paths 89 | env: 90 | BINUTILS_LOC: ${{ steps.globals.outputs.BINUTILS_LOC }} 91 | CARGO_LOC: ${{ steps.globals.outputs.CARGO_LOC }} 92 | run: | 93 | echo "binutils-loc=$BINUTILS_LOC/bin" >> $GITHUB_OUTPUT 94 | echo "cargo-loc=$CARGO_LOC/bin" >> $GITHUB_OUTPUT 95 | shell: bash 96 | -------------------------------------------------------------------------------- /.github/workflows/audit.yaml: -------------------------------------------------------------------------------- 1 | name: Audit Prussia 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | paths: 7 | - '**/Cargo.toml' 8 | - '**/Cargo.lock' 9 | pull_request: 10 | 11 | permissions: 12 | actions: none 13 | attestations: none 14 | checks: none 15 | contents: none 16 | deployments: none 17 | id-token: none 18 | issues: none 19 | repository-projects: none 20 | discussions: none 21 | packages: none 22 | pages: none 23 | pull-requests: none 24 | security-events: none 25 | statuses: none 26 | 27 | 28 | jobs: 29 | audit: 30 | runs-on: ubuntu-latest 31 | 32 | steps: 33 | - name: Checkout repository 34 | uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 35 | with: 36 | persist-credentials: false 37 | 38 | - name: Set up build env 39 | id: build-env 40 | uses: ./.github/actions/setup-build-env 41 | 42 | - name: Set up PATH 43 | env: 44 | BINUTILS_LOC: ${{ steps.build-env.outputs.binutils-loc }} 45 | CARGO_LOC: ${{ steps.build-env.outputs.cargo-loc }} 46 | run: | 47 | echo $BINUTILS_LOC >> $GITHUB_PATH 48 | echo $CARGO_LOC >> $GITHUB_PATH 49 | 50 | - name: Audit checks 51 | uses: rustsec/audit-check@69366f33c96575abad1ee0dba8212993eecbe998 52 | with: 53 | token: ${{ secrets.GITHUB_TOKEN }} 54 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: Build Prussia 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | 8 | permissions: 9 | actions: none 10 | attestations: none 11 | checks: none 12 | contents: none 13 | deployments: none 14 | id-token: none 15 | issues: none 16 | repository-projects: none 17 | discussions: none 18 | packages: none 19 | pages: none 20 | pull-requests: none 21 | security-events: none 22 | statuses: none 23 | 24 | 25 | jobs: 26 | build: 27 | runs-on: ubuntu-latest 28 | 29 | steps: 30 | - name: Checkout repository 31 | uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 32 | with: 33 | persist-credentials: false 34 | 35 | - name: Set up build env 36 | id: build-env 37 | uses: ./.github/actions/setup-build-env 38 | 39 | - name: Set up PATH 40 | env: 41 | BINUTILS_LOC: ${{ steps.build-env.outputs.binutils-loc }} 42 | CARGO_LOC: ${{ steps.build-env.outputs.cargo-loc }} 43 | run: | 44 | echo $BINUTILS_LOC >> $GITHUB_PATH 45 | echo $CARGO_LOC >> $GITHUB_PATH 46 | 47 | - name: Assemble ASM deps 48 | working-directory: ./prussia_rt 49 | run: | 50 | ./rebuild-asm-lib.sh 51 | 52 | - name: Build hello-rs 53 | run: | 54 | cargo build --release -p hello-rs 55 | 56 | - name: Build biostation 57 | run: | 58 | cargo build --release -p biostation 59 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.un~ 2 | *.elf 3 | target/ 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "svd2rust"] 2 | path = svd2rust 3 | url = https://github.com/rust-embedded/svd2rust/ 4 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | SPDX-License-Identifier: MIT OR Apache-2.0 2 | 3 | Copyright (C) Dan Ravensloft 2018 4 | 5 | In layman's terms: the same license as Rust itself. 6 | 7 | Note that I have in some cases used PS2SDK as a reference, which is licensed under the Academic Free License 2.0. 8 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 4 4 | 5 | [[package]] 6 | name = "aligned" 7 | version = "0.3.5" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "3a785a543aea40f5e4e2e93bb2655d31bc21bb391fff65697150973e383f16bb" 10 | dependencies = [ 11 | "as-slice", 12 | ] 13 | 14 | [[package]] 15 | name = "as-slice" 16 | version = "0.1.5" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "45403b49e3954a4b8428a0ac21a4b7afadccf92bfd96273f1a58cd4812496ae0" 19 | dependencies = [ 20 | "generic-array 0.12.4", 21 | "generic-array 0.13.3", 22 | "generic-array 0.14.7", 23 | "stable_deref_trait", 24 | ] 25 | 26 | [[package]] 27 | name = "biostation" 28 | version = "0.0.0" 29 | dependencies = [ 30 | "prussia_debug", 31 | "prussia_dma", 32 | "prussia_intc", 33 | "prussia_rt", 34 | "xmas-elf", 35 | ] 36 | 37 | [[package]] 38 | name = "bitflags" 39 | version = "1.3.2" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 42 | 43 | [[package]] 44 | name = "generic-array" 45 | version = "0.12.4" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" 48 | dependencies = [ 49 | "typenum", 50 | ] 51 | 52 | [[package]] 53 | name = "generic-array" 54 | version = "0.13.3" 55 | source = "registry+https://github.com/rust-lang/crates.io-index" 56 | checksum = "f797e67af32588215eaaab8327027ee8e71b9dd0b2b26996aedf20c030fce309" 57 | dependencies = [ 58 | "typenum", 59 | ] 60 | 61 | [[package]] 62 | name = "generic-array" 63 | version = "0.14.7" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" 66 | dependencies = [ 67 | "typenum", 68 | "version_check", 69 | ] 70 | 71 | [[package]] 72 | name = "hello-rs" 73 | version = "0.1.0" 74 | dependencies = [ 75 | "panic-halt", 76 | "prussia_bios", 77 | "prussia_dma", 78 | "prussia_rt", 79 | ] 80 | 81 | [[package]] 82 | name = "panic-halt" 83 | version = "0.2.0" 84 | source = "registry+https://github.com/rust-lang/crates.io-index" 85 | checksum = "de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812" 86 | 87 | [[package]] 88 | name = "playstation2" 89 | version = "0.1.3" 90 | dependencies = [ 91 | "vcell", 92 | ] 93 | 94 | [[package]] 95 | name = "prussia_bios" 96 | version = "0.1.0" 97 | 98 | [[package]] 99 | name = "prussia_debug" 100 | version = "0.1.0" 101 | 102 | [[package]] 103 | name = "prussia_dma" 104 | version = "0.2.2" 105 | dependencies = [ 106 | "aligned", 107 | "bitflags", 108 | ] 109 | 110 | [[package]] 111 | name = "prussia_intc" 112 | version = "0.1.0" 113 | dependencies = [ 114 | "bitflags", 115 | ] 116 | 117 | [[package]] 118 | name = "prussia_rt" 119 | version = "0.4.2" 120 | dependencies = [ 121 | "bitflags", 122 | "r0", 123 | ] 124 | 125 | [[package]] 126 | name = "r0" 127 | version = "0.2.2" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | checksum = "e2a38df5b15c8d5c7e8654189744d8e396bddc18ad48041a500ce52d6948941f" 130 | 131 | [[package]] 132 | name = "stable_deref_trait" 133 | version = "1.2.0" 134 | source = "registry+https://github.com/rust-lang/crates.io-index" 135 | checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" 136 | 137 | [[package]] 138 | name = "typenum" 139 | version = "1.17.0" 140 | source = "registry+https://github.com/rust-lang/crates.io-index" 141 | checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" 142 | 143 | [[package]] 144 | name = "vcell" 145 | version = "0.1.3" 146 | source = "registry+https://github.com/rust-lang/crates.io-index" 147 | checksum = "77439c1b53d2303b20d9459b1ade71a83c716e3f9c34f3228c00e6f185d6c002" 148 | 149 | [[package]] 150 | name = "version_check" 151 | version = "0.9.5" 152 | source = "registry+https://github.com/rust-lang/crates.io-index" 153 | checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" 154 | 155 | [[package]] 156 | name = "xmas-elf" 157 | version = "0.10.0" 158 | source = "registry+https://github.com/rust-lang/crates.io-index" 159 | checksum = "18245fcbb8b3de8dd198ce7944fdd4096986fd6cd306b0fcfa27df817bd545d6" 160 | dependencies = [ 161 | "zero", 162 | ] 163 | 164 | [[package]] 165 | name = "zero" 166 | version = "0.1.3" 167 | source = "registry+https://github.com/rust-lang/crates.io-index" 168 | checksum = "2fe21bcc34ca7fe6dd56cc2cb1261ea59d6b93620215aefb5ea6032265527784" 169 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | members = [ 4 | "biostation", 5 | "hello-rs", 6 | "prussia_debug", 7 | "prussia_dma", 8 | "prussia_intc", 9 | "prussia_rt", 10 | "playstation2-pac-rs" 11 | ] 12 | 13 | [profile.dev] 14 | panic = "abort" 15 | 16 | [profile.release] 17 | panic = "abort" 18 | lto = true 19 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | gen_svd: 3 | @echo Generating lib.rs 4 | @svd2rust --strict -i ps2.xml --target none --output-dir playstation2-pac-rs/src 5 | @echo Formatting 6 | @rustfmt playstation2-pac-rs/src/lib.rs 7 | @echo Done 8 | 9 | analyse_workflows: 10 | zizmor -p .github/**/* 11 | 12 | install_recommended_cargo_subcommands: 13 | cargo install --locked \ 14 | zizmor \ 15 | cargo-audit -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Prussia - a Rust PS2 SDK. 2 | 3 | I can be found in the Freenode IRC channel #psugnd, or in the EmuDev discord (https://discord.gg/dkmJAes). 4 | 5 | ## Lift Pitch - Why use Rust on the PS2? 6 | 7 | - The PlayStation 2 is fairly cheap (~£40) at current prices, making it easy to obtain. It has many features: a capable GPU, embedded SIMD units, sound, controller, network and memory card support. 8 | - Rust is a modern language with a large ecosystem, and its emphasis on safety avoids a whole class of bugs. It is also fast, being competitive with C and C++. 9 | - Rust can be used to express side-effects of the PS2's hardware and avoid things like DMA reading unallocated memory. 10 | 11 | ## Okay, how do I get started? 12 | 13 | ### Prerequisites: PS2 14 | 15 | You will need a memory card that has Free MCBoot to load unsigned code (memory cards with Free MCBoot installed can be found cheaply on eBay), and a *high-loading* (`LOADHIGH = 1` in the Makefile) version of [PS2Link](https://github.com/ps2dev/ps2link) on the PS2 memory card. 16 | 17 | On your computer, you will need Linux (On Windows, a Linux VM may work, but WSL currently does not; macOS is untested), [PS2Client](https://github.com/ps2dev/ps2client), [binutils for MIPS](https://ftp.gnu.org/gnu/binutils/) and [nightly Rust](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#rustup-and-the-role-of-rust-nightly). 18 | 19 | ### Prerequisites: PC 20 | 21 | You will need a *legal* PS2 BIOS dump, plus [PCSX2](https://pcsx2.net), [binutils for MIPS](https://ftp.gnu.org/gnu/binutils/) and [nightly Rust](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#rustup-and-the-role-of-rust-nightly). 22 | 23 | The PCSX2 first-time wizard will let you select your BIOS. 24 | 25 | ### Creating a project 26 | 27 | As Prussia is not currently on crates.io, create a new project with `cargo new --bin project_name` in the Prussia root directory. Then copy `ps2.json` (which can be found in the `hello-rs` project) into your new project's root directory. 28 | 29 | ### An example project 30 | 31 | Prussia does not (yet) support the Rust Standard Library, so you will be working in `#![no_std]` land. 32 | 33 | Here is a bare-bones example `src/main.rs`: 34 | ```rust 35 | #![no_std] 36 | #![no_main] 37 | 38 | extern crate panic_halt; 39 | extern crate prussia_rt; 40 | 41 | #[no_mangle] 42 | fn main() -> ! { 43 | loop {} 44 | } 45 | ``` 46 | Plus an example `Cargo.toml` to go with it: 47 | ```toml 48 | [package] 49 | name = "project_name" 50 | version = "0.1.0" 51 | authors = ["John Smith ", "Jane Bloggs "] 52 | edition = "2018" 53 | 54 | [dependencies] 55 | panic-halt = "0.2.0" 56 | prussia_rt = { path = "../prussia_rt" } 57 | 58 | [profile.dev] 59 | panic = "abort" 60 | 61 | [profile.release] 62 | panic = "abort" 63 | ``` 64 | And `.cargo/config.toml`: 65 | ```toml 66 | [build] 67 | target = "./ps2.json" 68 | 69 | [unstable] 70 | build-std = ["core", "compiler_builtins"] 71 | build-std-features = ["compiler-builtins-mem"] 72 | ``` 73 | 74 | ### Building your project 75 | 76 | To build your project, run `cargo build` from the root directory of your crate. 77 | 78 | ### Running your project: PS2: PS2Link 79 | 80 | You will need to launch PS2Link through either a Free MCBoot entry/hotkey (both of which can be set through the Free McBoot Configurator), or through uLaunchELF. It will block until it can configure the network, so if it does not show "Ready" after about 10 seconds, make sure your Ethernet cable is plugged in (if you have an SCPH-3xxxx console which does not come with an Ethernet port, you can get an Ethernet adapter which plugs into the back). 81 | 82 | You will also need to find the name of your executable, which should be in `target/ps2/debug/`. 83 | 84 | When PS2Link shows "Ready" on the screen, `ps2client execee host:path/to/executable`, and PS2Link will download and run your executable. 85 | 86 | At the moment you will need to reset your console to run a new program, but when yielding support is implemented in PruSSia, then you could use `ps2client reset` to return to PS2Link. 87 | 88 | ### Running your project: PS2: uLaunchELF 89 | 90 | You can also put your executable on a FAT32-formatted USB stick, and run it through the menus of uLaunchELF, although there is no possibility of remotely resetting your program after you have finished; you will need to use the power button to reset the console. 91 | 92 | ### Running your project: PCSX2 93 | 94 | PCSX2 offers a "Run ELF" option under the System menu, that will let you select your executable to run. 95 | 96 | ## Features 97 | 98 | - Startup/bootstrapping crate (`prussia_rt`) 99 | - Direct Memory Access Controller crate (`prussia_dma` - WIP) 100 | 101 | ## TODO (in rough order) 102 | 103 | - GS Interface (GIF) to Graphics Synthesizer - requires `prussia_dma` 104 | - SBUS Interface (SIF) to Input/Output Processor - requires `prussia_dma` 105 | - Console I/O - requires SIF 106 | - Controller I/O - requires SIF 107 | - Sound Output - requires SIF 108 | - Memory Card I/O - requires SIF 109 | - DEV9 (hard disk/ethernet controller) I/O - requires SIF 110 | - Ethernet I/O - requires DEV9 111 | - Hard Disk I/O - requires DEV9 112 | - VU Interface 0 (VIF0) to Vector Unit 0 - requires `prussia_dma` 113 | - VU Interface 1 (VIF1) to Vector Unit 1 - requires `prussia_dma` 114 | - Image Processing Unit - requires `prussia_dma` 115 | -------------------------------------------------------------------------------- /biostation/COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /biostation/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "biostation" 3 | version = "0.0.0" 4 | authors = ["Dan Ravensloft "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | prussia_debug = { path = "../prussia_debug" } 9 | prussia_dma = { path = "../prussia_dma" } 10 | prussia_intc = { path = "../prussia_intc" } 11 | prussia_rt = { path = "../prussia_rt" } 12 | xmas-elf = "0.10" 13 | -------------------------------------------------------------------------------- /biostation/README.md: -------------------------------------------------------------------------------- 1 | # Biostation - FOSS PlayStation 2 BIOS. 2 | 3 | The aim of Biostation is to remove the need for a copyrighted Sony BIOS in emulators. 4 | 5 | # TODO: 6 | 7 | - Port [current code](https://github.com/ZirconiumX/biostation) from C to Rust. 8 | - Fill out the system call table (currently about 160 known syscalls). 9 | 10 | # License 11 | 12 | This program is free software: you can redistribute it and/or modify 13 | it under the terms of the GNU General Public License as published by 14 | the Free Software Foundation, either version 3 of the License, or 15 | (at your option) any later version. 16 | 17 | This program is distributed in the hope that it will be useful, 18 | but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | GNU General Public License for more details. 21 | 22 | You should have received a copy of the GNU General Public License 23 | along with this program. If not, see . 24 | -------------------------------------------------------------------------------- /biostation/build.rs: -------------------------------------------------------------------------------- 1 | use std::{env, error::Error, fs::File, io::Write, path::PathBuf}; 2 | 3 | fn main() -> Result<(), Box> { 4 | let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); 5 | 6 | // extend the library search path 7 | println!("cargo:rustc-link-search={}", out_dir.display()); 8 | 9 | // override user `linkfile.ld` in the build directory 10 | File::create(out_dir.join("linkfile.ld"))?.write_all(include_bytes!("kernel-linkfile.ld"))?; 11 | 12 | Ok(()) 13 | } 14 | -------------------------------------------------------------------------------- /biostation/kernel-linkfile.ld: -------------------------------------------------------------------------------- 1 | /* SPDX-License-Identifier: GPL-3.0-or-later */ 2 | 3 | ENTRY(_start); 4 | 5 | SECTIONS { 6 | .text 0x00000000 : { 7 | KEEP(*(.ee_exc_tlbmiss)); 8 | 9 | . = 0x080; 10 | KEEP(*(.ee_exc_counter)); 11 | 12 | . = 0x100; 13 | KEEP(*(.ee_exc_debug)); 14 | 15 | . = 0x180; 16 | KEEP(*(.ee_exc_common)); 17 | 18 | . = 0x200; 19 | KEEP(*(.ee_exc_interrupt)); 20 | 21 | . = 0x280; 22 | *(.text .text.*); 23 | } 24 | 25 | .data : { 26 | *(.rodata .rodata.*); 27 | *(.data .data.*); 28 | } 29 | 30 | .bss : { 31 | START_OF_BSS = .; 32 | *(.bss .bss.*); 33 | } 34 | 35 | END_OF_BSS = .; 36 | } 37 | -------------------------------------------------------------------------------- /biostation/src/cache/mod.rs: -------------------------------------------------------------------------------- 1 | //! Operations on the EE caches. 2 | 3 | #[no_mangle] 4 | pub extern "C" fn flush(_mode: u32) { 5 | // unimplemented 6 | } 7 | -------------------------------------------------------------------------------- /biostation/src/exceptions/common/handler.S: -------------------------------------------------------------------------------- 1 | .section .ee_exc_common, "a" 2 | .ent common_handler 3 | common_handler: 4 | mfc0 $k0, $13 // Load Cause register. 5 | andi $k0, 0x3F // Extract Cause.ExcCode. 6 | 7 | addi $sp, -20 // Save $ra and $t0. 8 | sw $ra, 0($sp) 9 | sw $t0, 16($sp) 10 | 11 | la $t0, COMMON_HANDLERS // Load start of handler table. 12 | add $k0, $t0 // Add ExcCode to handler table. 13 | 14 | lw $t0, 16($sp) // Restore $t0 from stack. 15 | 16 | lw $k0, 0($k0) // Get the handler address. 17 | jalr $k0 // Jump to the handler. 18 | 19 | lw $ra, 0($sp) // Restore $ra from stack. 20 | addi $sp, 20 // Pop stack. 21 | 22 | .int 0x0000000f // sync 23 | .int 0x42000018 // eret 24 | .end common_handler 25 | 26 | .section .bss 27 | COMMON_HANDLERS: 28 | .space 16*4 29 | -------------------------------------------------------------------------------- /biostation/src/exceptions/common/mod.rs: -------------------------------------------------------------------------------- 1 | use core::arch::global_asm; 2 | 3 | use prussia_rt::cop0; 4 | 5 | mod syscall; 6 | 7 | global_asm!(include_str!("handler.S")); 8 | 9 | extern "C" { 10 | static mut COMMON_HANDLERS: [usize; 16]; 11 | } 12 | 13 | #[no_mangle] 14 | extern "C" fn unimplemented_common_handler() { 15 | let exc_code = (cop0::Cause::load() & cop0::Cause::EXC_CODE).bits() >> 2; 16 | let exc_code = cop0::L1Exception::try_from_common(exc_code as u8) 17 | .expect("Exception codes are between 1 and 13 on real hardware"); 18 | 19 | unimplemented!("Exception {:?} handler", exc_code); 20 | } 21 | 22 | pub fn init() { 23 | unsafe { 24 | for x in COMMON_HANDLERS.iter_mut() { 25 | *x = unimplemented_common_handler as usize; 26 | } 27 | 28 | COMMON_HANDLERS[9] = syscall::syscall_handler as usize; 29 | } 30 | syscall::init(); 31 | } 32 | -------------------------------------------------------------------------------- /biostation/src/exceptions/common/syscall/handler.S: -------------------------------------------------------------------------------- 1 | .extern init_main_thread 2 | 3 | .text 4 | .globl syscall_handler 5 | .ent syscall_handler 6 | syscall_handler: 7 | addi $sp, -16 // Save $ra to stack. 8 | sw $ra, 0($sp) 9 | 10 | la $k0, SYSCALL_HANDLERS // Load the start of the syscall table. 11 | andi $v1, 0x7F // Mask out the "sign" bit of the syscall. 12 | sll $v1, 2 // Convert syscall number to index. 13 | addu $k0, $3 // Calculate the syscall table offset. 14 | lw $k0, 0($k0) // Find the handler address. 15 | 16 | jalr $k0 // Jump to it. 17 | 18 | lw $ra, 0($sp) // Restore $ra from stack. 19 | addi $sp, 16 20 | 21 | mfc0 $k0, $14 // Increment EPC to run the next instruction. 22 | addi $k0, 4 23 | mtc0 $k0, $14 24 | 25 | jr $ra 26 | .end syscall_handler 27 | 28 | .section .bss 29 | SYSCALL_HANDLERS: 30 | .space 128*4 31 | -------------------------------------------------------------------------------- /biostation/src/exceptions/common/syscall/mod.rs: -------------------------------------------------------------------------------- 1 | use core::arch::{asm, global_asm}; 2 | 3 | use crate::cache; 4 | use crate::gs; 5 | use crate::thread; 6 | 7 | global_asm!(include_str!("handler.S")); 8 | 9 | extern "C" { 10 | static mut SYSCALL_HANDLERS: [usize; 128]; 11 | 12 | /// Assembly dispatch function for system calls. 13 | pub fn syscall_handler(); 14 | } 15 | 16 | #[no_mangle] 17 | extern "C" fn unimplemented_syscall_handler() { 18 | let syscall_num: u32; 19 | unsafe { asm!(".set noat; move {}, $v1", out(reg) syscall_num) }; 20 | unimplemented!("Handler for syscall {:x}", syscall_num); 21 | } 22 | 23 | pub fn init() { 24 | unsafe { 25 | for x in SYSCALL_HANDLERS.iter_mut() { 26 | *x = unimplemented_syscall_handler as usize; 27 | } 28 | 29 | SYSCALL_HANDLERS[0x3C] = thread::init_main_thread as usize; 30 | SYSCALL_HANDLERS[0x3D] = thread::init_heap as usize; 31 | SYSCALL_HANDLERS[0x64] = cache::flush as usize; 32 | SYSCALL_HANDLERS[0x70] = gs::imr::imr as usize; 33 | SYSCALL_HANDLERS[0x71] = gs::imr::put_imr as usize; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /biostation/src/exceptions/mod.rs: -------------------------------------------------------------------------------- 1 | mod common; 2 | 3 | pub fn init() { 4 | common::init(); 5 | } 6 | -------------------------------------------------------------------------------- /biostation/src/gs/imr.rs: -------------------------------------------------------------------------------- 1 | use prussia_rt::atomic; 2 | 3 | /// The Graphics Synthesizer Interrupt Mask Register. 4 | const GS_IMR: usize = 0x1200_1010; 5 | 6 | /// A local version of the IMR. Only valid if accessed exclusively through this API. 7 | static mut IMR: u64 = 0x0000_7F00; 8 | 9 | pub extern "C" fn imr() -> u64 { 10 | unsafe { IMR } 11 | } 12 | 13 | pub extern "C" fn put_imr(imr: u64) { 14 | atomic::write_u64(GS_IMR, imr); 15 | 16 | unsafe { 17 | IMR = imr; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /biostation/src/gs/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod imr; 2 | -------------------------------------------------------------------------------- /biostation/src/main.rs: -------------------------------------------------------------------------------- 1 | //! A PlayStation 2 BIOS written in Rust. 2 | 3 | #![no_std] 4 | #![no_main] 5 | #![deny( 6 | missing_docs, 7 | missing_debug_implementations, 8 | trivial_casts, 9 | trivial_numeric_casts 10 | )] 11 | #![feature(asm_experimental_arch)] 12 | #![feature(naked_functions)] 13 | #![feature(core_intrinsics)] 14 | 15 | extern crate prussia_dma as dma; 16 | extern crate prussia_intc as intc; 17 | 18 | use core::fmt::Write; 19 | use core::intrinsics; 20 | use core::mem; 21 | use core::panic::PanicInfo; 22 | use core::ptr; 23 | use core::slice; 24 | use core::str; 25 | 26 | use prussia_debug::EEOut; 27 | use prussia_rt::{cop0, interrupts}; 28 | use xmas_elf::ElfFile; 29 | 30 | mod cache; 31 | mod exceptions; 32 | mod gs; 33 | mod romdir; 34 | mod thread; 35 | 36 | #[panic_handler] 37 | fn panic(info: &PanicInfo) -> ! { 38 | // Write the panic message to EE output. 39 | let mut out = EEOut; 40 | writeln!(out, "[EE] {}", info).unwrap(); 41 | 42 | // Then crash to trigger the emulator. 43 | // This gets converted to `break` by LLVM. 44 | intrinsics::abort(); 45 | } 46 | 47 | #[no_mangle] 48 | fn main() -> ! { 49 | let mut out = EEOut; 50 | writeln!(out, "[EE] Hello, world!").unwrap(); 51 | 52 | // Disable spurious interrupts while setting up. 53 | interrupts::disable(); 54 | 55 | // Stop interrupts from the interrupt controller. 56 | // Remember that writing 1 to a mask toggles it; so writing it to itself clears it. 57 | intc::Mask::load().store(); 58 | 59 | // And from the DMA controller. 60 | dma::Status::load().store(); 61 | 62 | // Set up the exception tables. 63 | exceptions::init(); 64 | 65 | // Switch to our exception tables. 66 | let mut status = cop0::Status::load(); 67 | status &= !cop0::Status::BEV; 68 | status.store(); 69 | 70 | // Enable interrupts now that we've set everything up. 71 | interrupts::enable(); 72 | 73 | writeln!(out, "[EE] Init OK").unwrap(); 74 | 75 | // Fetch the payload address. 76 | let (addr, entry) = romdir::lookup(b"PILLGEN\0\0\0").expect("Failed to find PILLGEN in ROM"); 77 | 78 | // Load the ELF file. 79 | writeln!( 80 | out, 81 | "[EE] Found {} at {:x}", 82 | str::from_utf8(&entry.name).unwrap(), 83 | addr 84 | ) 85 | .unwrap(); 86 | 87 | let data = unsafe { slice::from_raw_parts(addr as *mut u8, entry.size as usize) }; 88 | let elf = ElfFile::new(data).expect("ELF should be valid. This indicates a broken ROM build."); 89 | 90 | for header in elf.program_iter() { 91 | unsafe { 92 | ptr::copy_nonoverlapping( 93 | data[header.offset() as usize..].as_ptr(), 94 | header.physical_addr() as usize as *mut u8, 95 | header.file_size() as usize, 96 | ); 97 | writeln!( 98 | out, 99 | "[EE] copied {} bytes from {:x} to {:x}", 100 | header.file_size(), 101 | addr + (header.offset() as usize), 102 | header.physical_addr() 103 | ) 104 | .unwrap(); 105 | } 106 | } 107 | 108 | let elf_entry = elf.header.pt2.entry_point() as usize; 109 | 110 | writeln!(out, "[EE] Entry point is {:x}", elf_entry).unwrap(); 111 | 112 | let elf_entry: fn() = unsafe { mem::transmute(elf_entry as *mut u8) }; 113 | 114 | writeln!(out, "[EE] Launching payload").unwrap(); 115 | 116 | elf_entry(); 117 | 118 | unreachable!("Somehow returned from entry point"); 119 | } 120 | -------------------------------------------------------------------------------- /biostation/src/romdir/mod.rs: -------------------------------------------------------------------------------- 1 | /// A ROMDIR entry. 2 | #[repr(packed)] 3 | pub struct Entry { 4 | pub name: [u8; 10], 5 | _something: u16, 6 | pub size: u32, 7 | } 8 | 9 | const START_OF_ROM: usize = 0x1fc0_0000; 10 | const END_OF_ROM: usize = 0x2000_0000; 11 | 12 | /// Search for an entry in the ROM contents directory, returning a pointer to it if it exists. 13 | pub fn lookup(name: &[u8; 10]) -> Option<(usize, &Entry)> { 14 | let mut entry_addr: usize = START_OF_ROM; 15 | 16 | // Search for the start of the ROM directory. 17 | while entry_addr < END_OF_ROM { 18 | let entry_ptr = entry_addr as *const Entry; 19 | let entry_name = unsafe { &(*entry_ptr).name }; 20 | if entry_name == b"RESET\0\0\0\0\0" { 21 | break; 22 | } else { 23 | entry_addr += 1; 24 | } 25 | } 26 | 27 | // If we couldn't find the "RESET" entry, then this BIOS is very broken. 28 | if entry_addr == END_OF_ROM { 29 | panic!("Couldn't find start of ROM directory. This indicates a broken ROM build."); 30 | } 31 | 32 | // Check pointer alignment; MIPS requires 4 byte alignment for Entry::size. 33 | if entry_addr % 4 != 0 { 34 | panic!( 35 | "Start of ROM directory is not correctly aligned. This indicates a broken ROM build." 36 | ); 37 | } 38 | 39 | // Get the start of the entry, if it exists. 40 | let mut start_addr = START_OF_ROM; 41 | 42 | // Search for the matching ROM directory entry. 43 | while entry_addr < END_OF_ROM && start_addr < END_OF_ROM { 44 | let entry_ptr = entry_addr as *const Entry; 45 | let entry = unsafe { &*entry_ptr }; 46 | 47 | if &entry.name == name { 48 | return Some((start_addr, entry)); 49 | } else { 50 | entry_addr += 16; 51 | start_addr += entry.size as usize; 52 | } 53 | } 54 | 55 | // If we didn't find it in the ROM directory (which is probably a bug), return none. 56 | None 57 | } 58 | -------------------------------------------------------------------------------- /biostation/src/thread/glue.S: -------------------------------------------------------------------------------- 1 | .extern init_main_thread_rust 2 | 3 | .text 4 | .globl init_main_thread 5 | .ent init_main_thread 6 | init_main_thread: 7 | addi $sp, -20 8 | sw $t0, 16($sp) 9 | sw $ra, 0($sp) 10 | 11 | jal init_main_thread_rust 12 | 13 | lw $ra, 0($sp) 14 | lw $t0, 16($sp) 15 | addi $sp, 20 16 | 17 | jr $ra 18 | .end init_main_thread 19 | -------------------------------------------------------------------------------- /biostation/src/thread/mod.rs: -------------------------------------------------------------------------------- 1 | use core::{mem, arch::global_asm}; 2 | 3 | global_asm!(include_str!("glue.S")); 4 | 5 | /// The execution state of a thread. 6 | #[repr(C)] 7 | pub struct ThreadContext { 8 | /// EE general purpose registers. 9 | gprs: [u128; 32], 10 | /// ALU high register. 11 | hi: u128, 12 | /// ALU low register. 13 | lo: u128, 14 | /// Shft amount register. 15 | sa: u32, 16 | /// EE floating point registers. 17 | fprs: [u32; 32], 18 | /// Floating point accumulator. 19 | fp_acc: u32, 20 | /// Floating point unit control register. 21 | fp_ctrl: u32, 22 | } 23 | 24 | /// An EE kernel thread. 25 | #[derive(Copy, Clone, Debug)] 26 | struct Thread { 27 | /// Thread global pointer. 28 | gp: usize, 29 | /// Thread stack size. 30 | stack_size: usize, 31 | /// The bottom of the thread's stack. 32 | stack_bottom: usize, 33 | /// The top of the thread's heap. 34 | heap_top: usize, 35 | /// The thread context address. 36 | context: usize, 37 | /// Address to return to after the thread exits. 38 | return_address: usize, 39 | /// Thread arguments. 40 | args: usize, 41 | } 42 | 43 | impl Thread { 44 | fn new( 45 | gp: usize, 46 | stack_size: usize, 47 | stack_bottom: usize, 48 | return_address: usize, 49 | args: usize, 50 | ) -> Self { 51 | Thread { 52 | gp, 53 | stack_size, 54 | stack_bottom, 55 | heap_top: stack_bottom, 56 | context: stack_bottom + stack_size - mem::size_of::(), 57 | return_address, 58 | args, 59 | } 60 | } 61 | 62 | /// Return a mutable reference to this thread's register context. 63 | fn context_mut(&mut self) -> &mut ThreadContext { 64 | unsafe { &mut *(self.context as *mut ThreadContext) } 65 | } 66 | 67 | /// Return the top of a thread's stack, excluding the area of memory for the thread context. 68 | fn top_of_stack(&self) -> usize { 69 | self.context 70 | } 71 | 72 | /// Return the top of a thread's stack, including the area of memory for the thread context. 73 | fn absolute_top_of_stack(&self) -> usize { 74 | self.stack_bottom + self.stack_size 75 | } 76 | 77 | /// Return the bottom of a thread's stack. 78 | fn bottom_of_stack(&self) -> usize { 79 | self.stack_bottom 80 | } 81 | 82 | /// Return the top of a thread's heap. 83 | fn top_of_heap(&self) -> usize { 84 | self.heap_top 85 | } 86 | 87 | /// Set the top of a thread's heap. 88 | fn set_top_of_heap(&mut self, top: usize) { 89 | self.heap_top = top; 90 | } 91 | } 92 | 93 | /// The EE kernel thread state. 94 | struct KernelThreadState { 95 | threads: [Option; 256], 96 | current: u32, 97 | } 98 | 99 | impl KernelThreadState { 100 | const fn new() -> Self { 101 | KernelThreadState { 102 | threads: [None; 256], 103 | current: 0, 104 | } 105 | } 106 | 107 | /// Create the main thread, resetting internal state, and returning the thread ID of the main 108 | /// thread. 109 | fn create_main( 110 | &mut self, 111 | gp: usize, 112 | stack_size: usize, 113 | stack_bottom: usize, 114 | return_address: usize, 115 | args: usize, 116 | ) -> u32 { 117 | *self = KernelThreadState::new(); 118 | 119 | self.threads[self.current as usize] = Some(Thread::new( 120 | gp, 121 | stack_size, 122 | stack_bottom, 123 | return_address, 124 | args, 125 | )); 126 | 127 | self.current 128 | } 129 | 130 | /// Return a reference to the thread for a given ID. 131 | fn thread(&self, id: usize) -> &Option { 132 | &self.threads[id] 133 | } 134 | 135 | /// Return the current thread ID. 136 | fn current_thread(&self) -> u32 { 137 | self.current 138 | } 139 | } 140 | 141 | extern "C" { 142 | /// ABI adapter for init_main_thread_rust 143 | pub fn init_main_thread( 144 | gp: usize, 145 | stack_ptr: *mut u8, 146 | stack_size: usize, 147 | args: *mut u8, 148 | return_address: usize, 149 | ); 150 | } 151 | 152 | static mut THREAD_STATE: KernelThreadState = KernelThreadState::new(); 153 | 154 | const END_OF_RAM: usize = 0x0200_0000; 155 | 156 | /// Initialise the threading system, returning the stack pointer for the main thread. 157 | #[no_mangle] 158 | pub extern "C" fn init_main_thread_rust( 159 | gp: usize, 160 | mut stack_ptr: *mut u8, 161 | stack_size: usize, 162 | args: *mut u8, 163 | return_address: usize, 164 | ) -> usize { 165 | assert!( 166 | stack_size < END_OF_RAM, 167 | "Attempted to allocate more stack than available RAM" 168 | ); 169 | 170 | // A negative stack pointer means "put at the end of RAM". We give it a 4KiB buffer zone to 171 | // avoid stack smashing. 172 | if (stack_ptr as i32) < 0 { 173 | stack_ptr = (END_OF_RAM - (stack_size + 4096)) as *mut u8; 174 | } 175 | 176 | let id = unsafe { 177 | THREAD_STATE.create_main( 178 | gp, 179 | stack_size, 180 | stack_ptr as usize, 181 | return_address, 182 | args as usize, 183 | ) 184 | }; 185 | 186 | let mut thread = unsafe { THREAD_STATE.thread(id as usize).unwrap() }; 187 | 188 | let top_of_stack = thread.absolute_top_of_stack(); 189 | let ctx = thread.context_mut(); 190 | 191 | ctx.gprs[28] = gp as u128; // Global pointer. 192 | ctx.gprs[29] = top_of_stack as u128; // Stack pointer. 193 | ctx.gprs[30] = top_of_stack as u128; // Frame pointer. 194 | ctx.gprs[31] = return_address as u128; // Return address. 195 | 196 | thread.top_of_stack() 197 | } 198 | 199 | /// Initialise a thread's heap, returning the top of its heap. 200 | pub extern "C" fn init_heap(heap_bottom: usize, heap_size: i32) -> usize { 201 | let thread = unsafe { THREAD_STATE.current_thread() }; 202 | let mut thread = unsafe { THREAD_STATE.thread(thread as usize).unwrap() }; 203 | 204 | if heap_size < 0 { 205 | // A negative heap size means the top of the heap is the bottom of the stack. 206 | thread.set_top_of_heap(thread.bottom_of_stack()); 207 | } else { 208 | // A positive heap size means the heap is of a fixed size. 209 | thread.set_top_of_heap(heap_bottom + (heap_size as usize)); 210 | } 211 | 212 | thread.top_of_heap() 213 | } 214 | -------------------------------------------------------------------------------- /hello-rs/.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | target = "./ps2.json" 3 | 4 | [unstable] 5 | build-std = ["core", "compiler_builtins"] 6 | build-std-features = ["compiler-builtins-mem"] 7 | -------------------------------------------------------------------------------- /hello-rs/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /hello-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-rs" 3 | version = "0.1.0" 4 | authors = ["Dan Ravensloft "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | panic-halt = "0.2.0" 9 | prussia_bios = { path = "../prussia_bios" } 10 | prussia_dma = { path = "../prussia_dma" } 11 | prussia_rt = { path = "../prussia_rt" } 12 | -------------------------------------------------------------------------------- /hello-rs/ps2.json: -------------------------------------------------------------------------------- 1 | ../ps2.json -------------------------------------------------------------------------------- /hello-rs/src/main.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![no_main] 3 | 4 | extern crate panic_halt; 5 | extern crate prussia_bios as bios; 6 | extern crate prussia_dma as dma; 7 | extern crate prussia_rt as rt; 8 | 9 | #[no_mangle] 10 | fn main() -> ! { 11 | bios::exit(0); 12 | } 13 | -------------------------------------------------------------------------------- /playstation2-pac-rs/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "playstation2" 3 | version = "0.1.3" 4 | edition = "2018" 5 | description = "A Rust Peripheral Access Crate (PAC) for the PlayStation 2." 6 | homepage = "https://github.com/Ravenslofty/prussia/" 7 | repository = "https://github.com/Ravenslofty/prussia/" 8 | documentation = "https://docs.rs/playstation2" 9 | readme = "README.md" 10 | keywords = ["peripheral-access", "pac", "svd", "playstation2"] 11 | license = "MIT OR Apache-2.0" 12 | 13 | include = ["src/**/*", "Cargo.toml"] 14 | 15 | [lib] 16 | crate-type = ["lib"] 17 | 18 | [dependencies] 19 | vcell = "0.1.3" 20 | -------------------------------------------------------------------------------- /playstation2-pac-rs/README.md: -------------------------------------------------------------------------------- 1 | # playstation2-pac-rs 2 | A Rust Peripheral Access Crate (PAC) for the PlayStation 2. 3 | -------------------------------------------------------------------------------- /playstation2-pac-rs/rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly" 3 | components = ["rustfmt", "clippy", "rust-src", "llvm-tools"] 4 | -------------------------------------------------------------------------------- /prussia_bios/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "prussia_bios" 3 | version = "0.1.0" 4 | license = "MIT OR Apache-2.0" 5 | authors = ["Dan Ravensloft "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /prussia_bios/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A Rust implementation of the PlayStation 2 BIOS. 2 | 3 | #![no_std] 4 | #![deny(missing_docs)] 5 | #![feature(asm_experimental_arch)] 6 | 7 | use core::arch::asm; 8 | 9 | /// The Graphics Synthesizer video mode, passed to `set_gs_crt`. 10 | #[repr(i16)] 11 | pub enum VideoMode { 12 | /// PAL, 720x576@50Hz interlaced, as used in most of Europe. 13 | Pal = 2, 14 | /// NTSC, 720x480@59.97Hz interlaced, as used in North America and Japan. 15 | Ntsc = 3, 16 | } 17 | 18 | /// Whether interlacing is enabled, passed to `set_gs_crt`. 19 | #[repr(i16)] 20 | pub enum Interlacing { 21 | /// Do not interlace frames. 22 | Noninterlaced = 0, 23 | /// Interlace frames, blending between them. 24 | Interlaced = 1, 25 | } 26 | 27 | /// Whether to read every line or every other line, passed to `set_gs_crt`. 28 | #[repr(i16)] 29 | pub enum FieldFrameMode { 30 | /// Read every line from a frame. 31 | Frame = 0, 32 | /// Read every other line from a frame. 33 | Field = 1, 34 | } 35 | 36 | /// Configure the Graphics Synthesizer's display controller to output a given VideoMode. 37 | pub fn set_gs_crt(imode: Interlacing, vmode: VideoMode, ffmode: FieldFrameMode) { 38 | unsafe { 39 | asm!( 40 | "syscall", 41 | in("$3") 0x2, // v1 42 | in("$4") imode as i16, // a0 43 | in("$5") vmode as i16, // a1 44 | in("$6") ffmode as i16, // a2 45 | ); 46 | } 47 | } 48 | 49 | /// Exit the program and return to the PS2 browser. 50 | /// 51 | /// This function is not recommended for use if developing with PS2Link; it won't return to PS2Link 52 | /// but instead go straight to the browser, meaning you'll need to relaunch PS2Link. Instead, use 53 | /// `sleep_thread`. 54 | pub fn exit(return_code: u32) -> ! { 55 | unsafe { 56 | asm!( 57 | "syscall", 58 | in("$3") 0x4, // v1 59 | in("$4") return_code, // a0 60 | options(noreturn), 61 | ); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /prussia_debug/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "prussia_debug" 3 | version = "0.1.0" 4 | authors = ["Dan Ravensloft "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | -------------------------------------------------------------------------------- /prussia_debug/README.md: -------------------------------------------------------------------------------- 1 | # Debug output for the PlayStation 2's R5900 CPU 2 | -------------------------------------------------------------------------------- /prussia_debug/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Routines for BIOS debug output. 2 | #![no_std] 3 | #![deny(missing_docs)] 4 | 5 | use core::{fmt, ptr}; 6 | 7 | /// A zero-sized type for printing to the EE debug console. 8 | pub struct EEOut; 9 | 10 | static mut EE_DEBUG_OUT: *mut u8 = 0x1000_f180 as *mut u8; 11 | 12 | impl fmt::Write for EEOut { 13 | fn write_str(&mut self, s: &str) -> fmt::Result { 14 | for c in s.bytes() { 15 | unsafe { 16 | ptr::write_volatile(EE_DEBUG_OUT, c); 17 | } 18 | } 19 | Ok(()) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /prussia_dma/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "prussia_dma" 3 | version = "0.2.2" 4 | authors = ["Dan Ravensloft "] 5 | license = "MIT OR Apache-2.0" 6 | edition = "2018" 7 | 8 | [dependencies] 9 | aligned = "0.3.0" 10 | bitflags = "1.0.4" 11 | -------------------------------------------------------------------------------- /prussia_dma/README.md: -------------------------------------------------------------------------------- 1 | # `prussia_dma` - Direct Memory Access management routines. 2 | 3 | This crate contains routines to manage DMA transfers in a safe way. 4 | 5 | # Aliasing 6 | 7 | It is *very easy* to introduce memory aliasing. For example: 8 | 9 | ```rust 10 | use prussia_dma as dma; 11 | fn bad_idea(ipu_from: dma::IpuFrom, ipu_to: dma::IpuTo) -> (dma::IpuFrom, dma::IpuTo) { 12 | static mut BUFFER: Aligned = Aligned([0; 4]); 13 | 14 | let dma_from = dma::Transfer::from_mem(ipu_to, unsafe { &mut BUFFER }); // Safe. 15 | let dma_to = dma::Transfer::to_mem(ipu_from, unsafe { &mut BUFFER }); // UNSAFE; introduces memory aliasing. 16 | 17 | let (ipu_to, _) = dma_from.wait(); 18 | let (ipu_from, _) = dma_to.wait(); 19 | 20 | (ipu_from, ipu_to) 21 | } 22 | ``` 23 | 24 | While this problem is fixed easily enough: 25 | ```rust 26 | use prussia_dma as dma; 27 | fn better(ipu_from: dma::IpuFrom, ipu_to: dma::IpuTo) -> (dma::IpuFrom, dma::IpuTo) { 28 | static mut BUFFER: Aligned = Aligned([0; 4]); 29 | 30 | let dma_from = dma::Transfer::from_mem(ipu_to, unsafe { &mut BUFFER }); // Safe. 31 | let (ipu_to, _) = dma_from.wait(); 32 | 33 | let dma_to = dma::Transfer::to_mem(ipu_from, unsafe { &mut BUFFER }); // UNSAFE; introduces memory aliasing. 34 | let (ipu_from, _) = dma_to.wait(); 35 | 36 | (ipu_from, ipu_to) 37 | } 38 | ``` 39 | I don't yet have anything like `cortex_m::singleton!()`, so consider using a `RefCell`, or one of the `spin` crate `Mutex`es. 40 | 41 | ## TODO 42 | 43 | This seems reasonably complete at the moment, aside from a `singleton!` equivalent, which might better belong in `prussia_rt`.. 44 | 45 | -------------------------------------------------------------------------------- /prussia_dma/ps2.json: -------------------------------------------------------------------------------- 1 | ../ps2.json -------------------------------------------------------------------------------- /prussia_dma/src/control.rs: -------------------------------------------------------------------------------- 1 | //! DMA Controller interrupt handling. 2 | 3 | use core::ptr; 4 | 5 | use bitflags::bitflags; 6 | 7 | static mut DMAC_STAT: *mut u32 = 0x1000_e010 as *mut u32; 8 | 9 | bitflags! { 10 | /// DMA Controller interrupt status register. 11 | pub struct Status: u32 { 12 | /// Whether there is an interrupt on channel 0. 0 = no interrupt, 1 = interrupt. 13 | const CIS0 = 1; 14 | /// Whether there is an interrupt on channel 1. 0 = no interrupt, 1 = interrupt. 15 | const CIS1 = 1 << 1; 16 | /// Whether there is an interrupt on channel 2. 0 = no interrupt, 1 = interrupt. 17 | const CIS2 = 1 << 2; 18 | /// Whether there is an interrupt on channel 3. 0 = no interrupt, 1 = interrupt. 19 | const CIS3 = 1 << 3; 20 | /// Whether there is an interrupt on channel 4. 0 = no interrupt, 1 = interrupt. 21 | const CIS4 = 1 << 4; 22 | /// Whether there is an interrupt on channel 5. 0 = no interrupt, 1 = interrupt. 23 | const CIS5 = 1 << 5; 24 | /// Whether there is an interrupt on channel 6. 0 = no interrupt, 1 = interrupt. 25 | const CIS6 = 1 << 6; 26 | /// Whether there is an interrupt on channel 7. 0 = no interrupt, 1 = interrupt. 27 | const CIS7 = 1 << 7; 28 | /// Whether there is an interrupt on channel 8. 0 = no interrupt, 1 = interrupt. 29 | const CIS8 = 1 << 8; 30 | /// Whether there is an interrupt on channel 9. 0 = no interrupt, 1 = interrupt. 31 | const CIS9 = 1 << 9; 32 | /// Whether a DMA transfer has stalled. Requires Control::STD. 0 = no stall, 1 = stall at 33 | /// some point. 34 | const SIS = 1 << 13; 35 | /// Whether the DMA memory FIFO is empty. Requires Control::MFD. 0 = not empty, 1 = empty 36 | /// at some point. 37 | const MEIS = 1 << 14; 38 | /// Whether the DMA controller has encountered a bus error. 0 = no error, 1 = bus error. 39 | const BEIS = 1 << 15; 40 | /// Whether interrupts on channel 0 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 41 | const CIM0 = 1 << 16; 42 | /// Whether interrupts on channel 1 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 43 | const CIM1 = 1 << 17; 44 | /// Whether interrupts on channel 2 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 45 | const CIM2 = 1 << 18; 46 | /// Whether interrupts on channel 3 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 47 | const CIM3 = 1 << 19; 48 | /// Whether interrupts on channel 4 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 49 | const CIM4 = 1 << 20; 50 | /// Whether interrupts on channel 5 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 51 | const CIM5 = 1 << 21; 52 | /// Whether interrupts on channel 6 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 53 | const CIM6 = 1 << 22; 54 | /// Whether interrupts on channel 7 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 55 | const CIM7 = 1 << 23; 56 | /// Whether interrupts on channel 8 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 57 | const CIM8 = 1 << 24; 58 | /// Whether interrupts on channel 9 are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 59 | const CIM9 = 1 << 25; 60 | /// Whether DMA stall interrupts are active. 0 = disabled, 1 = enabled. Write 1 to toggle. 61 | const SIM = 1 << 29; 62 | /// Whether DMA memory FIFO interrupts are active. 0 = disabled, 1 = enabled. Write 1 to 63 | /// toggle. 64 | const MEIM = 1 << 30; 65 | } 66 | } 67 | 68 | impl Status { 69 | /// Load the DMA interrupt status register. 70 | pub fn load() -> Self { 71 | let status = unsafe { ptr::read_volatile(DMAC_STAT) }; 72 | Status { bits: status } 73 | } 74 | 75 | /// Store the DMA interrupt status register. 76 | pub fn store(self) { 77 | unsafe { ptr::write_volatile(DMAC_STAT, self.bits) } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /prussia_dma/src/devices/gif.rs: -------------------------------------------------------------------------------- 1 | use crate::devices::traits; 2 | 3 | /// The GS Interface, for writing data for the Graphics Synthesizer to render later. 4 | pub struct Gif; 5 | 6 | impl traits::Address for Gif { 7 | const CONTROL: *mut usize = 0x1000_a000 as *mut usize; 8 | const ADDRESS: *mut usize = 0x1000_a010 as *mut usize; 9 | const COUNT: *mut usize = 0x1000_a020 as *mut usize; 10 | } 11 | 12 | impl traits::WriteChannel for Gif {} 13 | -------------------------------------------------------------------------------- /prussia_dma/src/devices/ipu.rs: -------------------------------------------------------------------------------- 1 | use crate::devices::traits; 2 | 3 | /// The Image Processing Unit, for sending MPEG2 frames to be decoded. 4 | pub struct IpuFrom; 5 | /// The Image Processing Unit for receiving decoded MPEG2 frames. 6 | pub struct IpuTo; 7 | 8 | impl traits::Address for IpuFrom { 9 | const CONTROL: *mut usize = 0x1000_b000 as *mut usize; 10 | const ADDRESS: *mut usize = 0x1000_b010 as *mut usize; 11 | const COUNT: *mut usize = 0x1000_b020 as *mut usize; 12 | } 13 | 14 | impl traits::ReadChannel for IpuFrom {} 15 | 16 | impl traits::Address for IpuTo { 17 | const CONTROL: *mut usize = 0x1000_b400 as *mut usize; 18 | const ADDRESS: *mut usize = 0x1000_b410 as *mut usize; 19 | const COUNT: *mut usize = 0x1000_b420 as *mut usize; 20 | } 21 | 22 | impl traits::WriteChannel for IpuTo {} 23 | -------------------------------------------------------------------------------- /prussia_dma/src/devices/mod.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | 3 | mod gif; 4 | mod ipu; 5 | mod sif; 6 | mod spram; 7 | mod traits; 8 | mod vif; 9 | 10 | pub use crate::devices::gif::Gif; 11 | pub use crate::devices::ipu::{IpuFrom, IpuTo}; 12 | pub use crate::devices::sif::{Sif0, Sif1, Sif2}; 13 | pub use crate::devices::spram::{SpramFrom, SpramTo}; 14 | pub use crate::devices::traits::*; 15 | pub use crate::devices::vif::{Vif0, Vif1}; 16 | -------------------------------------------------------------------------------- /prussia_dma/src/devices/sif.rs: -------------------------------------------------------------------------------- 1 | use crate::devices::traits; 2 | 3 | /// SBUS Interface 0, for reading data from the Input/Output Processor. 4 | pub struct Sif0; 5 | /// SBUS Interface 1, for writing data to the Input/Output Processor. 6 | pub struct Sif1; 7 | /// SBUS Interface 2, for reading/writing debugging data to the Input/Output Processor. 8 | pub struct Sif2; 9 | 10 | impl traits::Address for Sif0 { 11 | const CONTROL: *mut usize = 0x1000_c000 as *mut usize; 12 | const ADDRESS: *mut usize = 0x1000_c010 as *mut usize; 13 | const COUNT: *mut usize = 0x1000_c020 as *mut usize; 14 | } 15 | 16 | impl traits::ReadChannel for Sif0 {} 17 | 18 | impl traits::Address for Sif1 { 19 | const CONTROL: *mut usize = 0x1000_c400 as *mut usize; 20 | const ADDRESS: *mut usize = 0x1000_c410 as *mut usize; 21 | const COUNT: *mut usize = 0x1000_c420 as *mut usize; 22 | } 23 | 24 | impl traits::WriteChannel for Sif1 {} 25 | 26 | impl traits::Address for Sif2 { 27 | const CONTROL: *mut usize = 0x1000_c800 as *mut usize; 28 | const ADDRESS: *mut usize = 0x1000_c810 as *mut usize; 29 | const COUNT: *mut usize = 0x1000_c820 as *mut usize; 30 | } 31 | 32 | impl traits::ReadChannel for Sif2 {} 33 | impl traits::WriteChannel for Sif2 {} 34 | -------------------------------------------------------------------------------- /prussia_dma/src/devices/spram.rs: -------------------------------------------------------------------------------- 1 | use crate::devices::traits; 2 | 3 | /// Scratchpad RAM, for fast data reads. 4 | pub struct SpramFrom; 5 | /// Scratchpad RAM, for fast data writes. 6 | pub struct SpramTo; 7 | 8 | impl traits::Address for SpramFrom { 9 | const CONTROL: *mut usize = 0x1000_d000 as *mut usize; 10 | const ADDRESS: *mut usize = 0x1000_d010 as *mut usize; 11 | const COUNT: *mut usize = 0x1000_d020 as *mut usize; 12 | } 13 | 14 | impl traits::ReadChannel for SpramFrom {} 15 | 16 | impl traits::Address for SpramTo { 17 | const CONTROL: *mut usize = 0x1000_d400 as *mut usize; 18 | const ADDRESS: *mut usize = 0x1000_d410 as *mut usize; 19 | const COUNT: *mut usize = 0x1000_d420 as *mut usize; 20 | } 21 | 22 | impl traits::WriteChannel for SpramTo {} 23 | -------------------------------------------------------------------------------- /prussia_dma/src/devices/traits.rs: -------------------------------------------------------------------------------- 1 | // Whether a channel can be read from. 2 | pub trait ReadChannel {} 3 | 4 | // Whether a channel can be written to. 5 | pub trait WriteChannel {} 6 | 7 | // Memory addresses for writing to a DMA channel. Not all channels have all addresses, so they are 8 | // marked as Option. 9 | pub trait Address { 10 | // Metadata and status control word. 11 | const CONTROL: *mut usize; 12 | // Memory address to read to/write from. 13 | const ADDRESS: *mut usize; 14 | // Number of 128-bit quadwords to read/write. 15 | const COUNT: *mut usize; 16 | // TAG_ADDRESS is used for devices that support DMA Chain Mode. However, we currently don't use 17 | // DMA Chain Mode, so it is irrelevant for now. 18 | // const TAG_ADDRESS: Option; 19 | } 20 | -------------------------------------------------------------------------------- /prussia_dma/src/devices/vif.rs: -------------------------------------------------------------------------------- 1 | use crate::devices::traits; 2 | 3 | /// VU Interface 0, for writing data to Vector Unit 0. 4 | pub struct Vif0; 5 | /// VU Interface 1, for reading/writing data to Vector Unit 1. 6 | pub struct Vif1; 7 | 8 | impl traits::Address for Vif0 { 9 | const CONTROL: *mut usize = 0x1000_8000 as *mut usize; 10 | const ADDRESS: *mut usize = 0x1000_8010 as *mut usize; 11 | const COUNT: *mut usize = 0x1000_8020 as *mut usize; 12 | } 13 | 14 | impl traits::WriteChannel for Vif0 {} 15 | 16 | impl traits::Address for Vif1 { 17 | const CONTROL: *mut usize = 0x1000_9000 as *mut usize; 18 | const ADDRESS: *mut usize = 0x1000_9010 as *mut usize; 19 | const COUNT: *mut usize = 0x1000_9020 as *mut usize; 20 | } 21 | 22 | impl traits::ReadChannel for Vif1 {} 23 | impl traits::WriteChannel for Vif1 {} 24 | -------------------------------------------------------------------------------- /prussia_dma/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! DMA Controller routines for the Sony PlayStation 2. 2 | //! 3 | //! The DMA Controller (DMAC) provides memory transfer for the peripherals of the PS2. Specifically 4 | //! it links to the GS Interface (GIF), the VU Interfaces (VIF0/VIF1), the SBUS Interface (SIF, for 5 | //! the Input/Output Processor) and the Image Processing Unit (IPU). 6 | //! 7 | //! Most DMA transfers are represented through the `Transfer` struct, and can be created through 8 | //! the `Transfer::from_mem` and `Transfer::to_mem` functions. 9 | //! 10 | //! Ownership of a channel is represented through the `Vif0`, `Vif1`, `Gif` (etc) types, which are 11 | //! moved into a `Transfer` while it is in progress to avoid multiple transfers on the same 12 | //! channel. A singleton for these channels is provided in `Channels::take()`. 13 | //! 14 | //! # Examples 15 | //! 16 | //! ``` 17 | //! use prussia_dma as dma; 18 | //! fn write_transfer(gif: dma::Gif) -> dma::Gif { 19 | //! // Note: don't actually send this to the GIF. 20 | //! static mut DATA: Aligned = Aligned([0xdeadbeef, 0xcafed00d, 0x0c0ffee0, 0xcafebabe]); 21 | //! 22 | //! let tx = dma::Transfer::from_mem(gif, unsafe { &mut DATA }); 23 | //! 24 | //! // Transfer in progress; don't touch DATA. 25 | //! // In future versions, there may be a better solution for avoiding memory aliasing. 26 | //! 27 | //! let (gif, _) = tx.wait(); 28 | //! 29 | //! // Modifying DATA is now safe. 30 | //! 31 | //! gif 32 | //! } 33 | //! ``` 34 | 35 | #![no_std] 36 | #![allow(dead_code)] 37 | #![deny(missing_docs)] 38 | 39 | extern crate aligned; 40 | 41 | use aligned::{Aligned, A16}; 42 | use core::{mem, ptr, sync::atomic}; 43 | 44 | mod control; 45 | mod devices; 46 | 47 | pub use crate::control::Status; 48 | pub use crate::devices::{Gif, IpuFrom, IpuTo, Sif0, Sif1, Sif2, SpramFrom, SpramTo, Vif0, Vif1}; 49 | 50 | /// Represents the channels of the DMA controller. 51 | pub struct Channels { 52 | vif0: Vif0, 53 | vif1: Vif1, 54 | gif: Gif, 55 | ipu_from: IpuFrom, 56 | ipu_to: IpuTo, 57 | sif0: Sif0, 58 | sif1: Sif1, 59 | sif2: Sif2, 60 | spram_from: SpramFrom, 61 | spram_to: SpramTo, 62 | } 63 | 64 | impl Channels { 65 | /// Return the DMA channels, *once*. 66 | pub fn take() -> Option { 67 | static mut TAKEN: bool = false; 68 | unsafe { 69 | if !TAKEN { 70 | TAKEN = true; 71 | Some(Self::steal()) 72 | } else { 73 | None 74 | } 75 | } 76 | } 77 | 78 | unsafe fn steal() -> Self { 79 | Channels { 80 | vif0: Vif0 {}, 81 | vif1: Vif1 {}, 82 | gif: Gif {}, 83 | ipu_from: IpuFrom {}, 84 | ipu_to: IpuTo {}, 85 | sif0: Sif0 {}, 86 | sif1: Sif1 {}, 87 | sif2: Sif2 {}, 88 | spram_from: SpramFrom {}, 89 | spram_to: SpramTo {}, 90 | } 91 | } 92 | 93 | /// Initialise a DMA channel. 94 | fn init(_dev: &mut T) { 95 | unsafe { 96 | // Zero the registers of the device. 97 | ptr::write_volatile(T::CONTROL, 0); 98 | ptr::write_volatile(T::ADDRESS, 0); 99 | ptr::write_volatile(T::COUNT, 0); 100 | } 101 | 102 | atomic::compiler_fence(atomic::Ordering::SeqCst); 103 | } 104 | 105 | /// Initialise and return the DMA channels. 106 | pub fn split( 107 | mut self, 108 | ) -> ( 109 | Vif0, 110 | Vif1, 111 | Gif, 112 | IpuFrom, 113 | IpuTo, 114 | Sif0, 115 | Sif1, 116 | Sif2, 117 | SpramFrom, 118 | SpramTo, 119 | ) { 120 | Channels::init(&mut self.vif0); 121 | Channels::init(&mut self.vif1); 122 | Channels::init(&mut self.gif); 123 | Channels::init(&mut self.ipu_from); 124 | Channels::init(&mut self.ipu_to); 125 | Channels::init(&mut self.sif0); 126 | Channels::init(&mut self.sif1); 127 | Channels::init(&mut self.sif2); 128 | Channels::init(&mut self.spram_from); 129 | Channels::init(&mut self.spram_to); 130 | 131 | ( 132 | self.vif0, 133 | self.vif1, 134 | self.gif, 135 | self.ipu_from, 136 | self.ipu_to, 137 | self.sif0, 138 | self.sif1, 139 | self.sif2, 140 | self.spram_from, 141 | self.spram_to, 142 | ) 143 | } 144 | } 145 | 146 | enum TransferDirection { 147 | ToMem, 148 | FromMem, 149 | } 150 | 151 | /// An in-progress DMA transfer. 152 | /// 153 | /// This struct holds a mutable reference to the data that it is operating on to ensure it does not 154 | /// go out of scope while the transfer is in progress. It also owns the channel that it is 155 | /// operating on to avoid multithread races. 156 | pub struct Transfer { 157 | data: &'static mut Aligned, 158 | dev: DEVICE, 159 | } 160 | 161 | impl Transfer { 162 | /// Perform a DMA transfer from a device to memory, and return a `Transfer` object bound to 163 | /// the destination object. 164 | /// 165 | /// Reading from a write-only device is prevented at compile time through use of internal marker 166 | /// traits. Reading zero quadwords has no effect. Correct alignment is ensured through use of 167 | /// `Aligned`. 168 | /// 169 | /// # Examples 170 | /// 171 | /// ``` 172 | /// let mut data = Aligned([0u32; 4]); 173 | /// { 174 | /// let transfer = Transfer::to_mem(SIF0, &mut data); 175 | /// // Do work. 176 | /// } 177 | /// // The contents of data are now one quadword from SIF0 (the IOP). 178 | /// ``` 179 | #[allow(clippy::wrong_self_convention)] 180 | pub fn to_mem(dev: DEVICE, data: &'static mut Aligned) -> Transfer { 181 | Transfer::transfer(TransferDirection::ToMem, dev, data) 182 | } 183 | } 184 | 185 | impl Transfer { 186 | /// Perform a DMA transfer from memory to a device, and return a `Transfer` object bound to 187 | /// the source object. 188 | /// 189 | /// Writing to a read-only device is prevented at compile time through use of internal marker 190 | /// traits. Writing zero quadwords has no effect. Correct alignment is ensured through use of 191 | /// `Aligned`. 192 | /// 193 | /// # Examples 194 | /// 195 | /// ``` 196 | /// let mut data = Aligned[0u32; 4]; 197 | /// { 198 | /// let transfer: Transfer = Transfer::from_mem(GIF, &mut data); 199 | /// // Do work. 200 | /// } 201 | /// // The contents of data have now been transferred to the GIF. 202 | /// ``` 203 | pub fn from_mem(dev: DEVICE, data: &'static mut Aligned) -> Transfer { 204 | Transfer::transfer(TransferDirection::FromMem, dev, data) 205 | } 206 | } 207 | 208 | impl Transfer { 209 | fn transfer( 210 | dir: TransferDirection, 211 | dev: DEVICE, 212 | data: &'static mut Aligned, 213 | ) -> Transfer { 214 | let address = data.as_ptr() as usize; 215 | // This assumes that data is on a 16-byte boundary. 216 | let qword_count: usize = (data.len() * mem::size_of::()) / 16; 217 | // The 1st bit of CHANNEL_CONTROL changes direction (we want to transfer from memory). 218 | // The 9th bit of CHANNEL_CONTROL starts a transfer. 219 | let control = unsafe { ptr::read_volatile(DEVICE::CONTROL) } | (1 << 8); 220 | let control = match dir { 221 | TransferDirection::ToMem => control & !1, 222 | TransferDirection::FromMem => control | 1, 223 | }; 224 | 225 | // The EE User's Manual (5.10 Restrictions) states not to initiate a DMA transfer with a 226 | // qword count of zero (possibly because it transfers zero qwords?). Either way, avoid this 227 | // situation, and because we don't set the STR bit, drop() will see a finished transaction 228 | // immediately. 229 | if qword_count != 0 { 230 | unsafe { 231 | // Memory address to read data from. 232 | ptr::write_volatile(DEVICE::ADDRESS, address); 233 | // Number of 128-bit quadwords to read. 234 | ptr::write_volatile(DEVICE::COUNT, qword_count); 235 | // Avoid compiler reordering. 236 | atomic::compiler_fence(atomic::Ordering::SeqCst); 237 | // Start the transfer. 238 | ptr::write_volatile(DEVICE::CONTROL, control); 239 | } 240 | } 241 | 242 | Transfer { data, dev } 243 | } 244 | 245 | /// Returns true if the DMA transfer has completed. 246 | pub fn is_done(&self) -> bool { 247 | // Check if the STR bit is zero. If we skipped transferring zero qwords in 248 | // to_mem()/from_mem() then this will be zero anyway. 249 | let control = unsafe { ptr::read_volatile(DEVICE::CONTROL) }; 250 | let control = control & (1 << 8); 251 | 252 | control == 0 253 | } 254 | 255 | /// Wait for a transfer to complete, returning the buffer used for the transfer. 256 | /// 257 | /// Failing to wait for a DMA transfer means it will continue to completion in the 258 | /// background, but the channel will remain locked. 259 | pub fn wait(self) -> (DEVICE, &'static mut Aligned) { 260 | while !self.is_done() {} 261 | 262 | atomic::compiler_fence(atomic::Ordering::SeqCst); 263 | 264 | (self.dev, self.data) 265 | } 266 | } 267 | 268 | mod tests { 269 | use aligned::{Aligned, A16}; 270 | 271 | use crate::Channels; 272 | use crate::Transfer; 273 | use crate::{Gif, IpuFrom, IpuTo, Sif0, Vif0, Vif1}; 274 | 275 | fn test_vif0(vif0: Vif0) -> Vif0 { 276 | static mut DATA: Aligned = Aligned([0u32; 4]); 277 | 278 | let dma = Transfer::from_mem(vif0, unsafe { &mut DATA }); 279 | let (vif0, _) = dma.wait(); 280 | 281 | vif0 282 | } 283 | 284 | fn test_vif1(vif1: Vif1) -> Vif1 { 285 | static mut DATA: Aligned = Aligned([0u32; 4]); 286 | 287 | let dma = Transfer::from_mem(vif1, unsafe { &mut DATA }); 288 | let (vif1, _) = dma.wait(); 289 | 290 | let dma = Transfer::to_mem(vif1, unsafe { &mut DATA }); 291 | let (vif1, _) = dma.wait(); 292 | 293 | vif1 294 | } 295 | 296 | fn test_gif(gif: Gif) -> Gif { 297 | static mut DATA: Aligned = Aligned([0u32; 4]); 298 | 299 | let dma = Transfer::from_mem(gif, unsafe { &mut DATA }); 300 | let (gif, _) = dma.wait(); 301 | 302 | gif 303 | } 304 | 305 | fn test_ipu(ipu_from: IpuFrom, ipu_to: IpuTo) -> (IpuFrom, IpuTo) { 306 | static mut READ_DATA: Aligned = Aligned([0u32; 4]); 307 | static mut WRITE_DATA: Aligned = Aligned([0u32; 4]); 308 | 309 | let dma_to = Transfer::from_mem(ipu_to, unsafe { &mut READ_DATA }); 310 | let dma_from = Transfer::to_mem(ipu_from, unsafe { &mut WRITE_DATA }); 311 | 312 | // Multiple transfers at once for fun and profit. 313 | // Note the separate read and write buffers; using the same buffer for multiple 314 | // simultaneous transfer is Undefined Behaviour. 315 | 316 | let (ipu_to, _) = dma_to.wait(); 317 | let (ipu_from, _) = dma_from.wait(); 318 | 319 | (ipu_from, ipu_to) 320 | } 321 | 322 | fn test_sif0(sif0: Sif0) -> Sif0 { 323 | static mut DATA: Aligned = Aligned([0u32; 4]); 324 | 325 | let dma = Transfer::to_mem(sif0, unsafe { &mut DATA }); 326 | let (sif0, _) = dma.wait(); 327 | 328 | sif0 329 | } 330 | 331 | // If this function compiles, this crate *should* be safe. 332 | fn test() { 333 | let chans = Channels::take().unwrap().split(); 334 | 335 | test_vif0(chans.0); 336 | test_vif1(chans.1); 337 | test_gif(chans.2); 338 | test_sif0(chans.5); 339 | } 340 | } 341 | -------------------------------------------------------------------------------- /prussia_intc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "prussia_intc" 3 | version = "0.1.0" 4 | authors = ["Dan Ravensloft "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | bitflags = "1.0.4" 9 | -------------------------------------------------------------------------------- /prussia_intc/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Routines for the PlayStation 2 Emotion Engine Interrupt Controller. 2 | 3 | #![no_std] 4 | #![deny(missing_docs)] 5 | use core::ptr; 6 | 7 | use bitflags::bitflags; 8 | 9 | static mut INTC_STAT: *mut u32 = 0x1000_f000 as *mut u32; 10 | static mut INTC_MASK: *mut u32 = 0x1000_f010 as *mut u32; 11 | 12 | bitflags! { 13 | /// The interrupt controller status. Each flag is set if the interrupt controller detects a 14 | /// change in state. Writing a bit acknowledges that interrupt. If the status and 15 | /// corresponding mask bit are both set, INT0 is raised. 16 | pub struct Status: u32 { 17 | /// An interrupt from the Graphics Synthesizer. 18 | const GS = 1; 19 | /// An interrupt from the SBUS connection to the IOP. 20 | const SBUS = 1 << 1; 21 | /// The start of VBlank. 22 | const VBON = 1 << 2; 23 | /// The end of VBlank. 24 | const VBOF = 1 << 3; 25 | /// An interrupt from VU Interface 0. 26 | const VIF0 = 1 << 4; 27 | /// An interrupt from VU Interface 1. 28 | const VIF1 = 1 << 5; 29 | /// An interrupt from Vector Unit 0. 30 | const VU0 = 1 << 6; 31 | /// An interrupt from Vector Unit 1. 32 | const VU1 = 1 << 7; 33 | /// An interrupt from the Image Processing Unit. 34 | const IPU = 1 << 8; 35 | /// An interrupt from Timer 0. 36 | const TIM0 = 1 << 9; 37 | /// An interrupt from Timer 1. 38 | const TIM1 = 1 << 10; 39 | /// An interrupt from Timer 2. 40 | const TIM2 = 1 << 11; 41 | /// An interrupt from Timer 3. 42 | const TIM3 = 1 << 12; 43 | /// An interrupt from the SBUS FIFO queue. 44 | const SFIFO = 1 << 13; 45 | /// An interrupt from the Vector Unit 0 watchdog. 46 | const VU0WD = 1 << 14; 47 | } 48 | } 49 | 50 | impl Status { 51 | /// Load the interrupt controller status. 52 | pub fn load() -> Self { 53 | let status = unsafe { ptr::read_volatile(INTC_STAT) }; 54 | Status { bits: status } 55 | } 56 | 57 | /// Store the interrupt controller status. 58 | pub fn store(self) { 59 | unsafe { ptr::write_volatile(INTC_STAT, self.bits) }; 60 | } 61 | } 62 | 63 | bitflags! { 64 | /// The interrupt status mask. Each bit is set if the interrupt is enabled and clear if the 65 | /// interrupt is disabled. Writing a bit toggles its state. If both the mask bit and the 66 | /// corresponding status bit are both set, INT0 is raised. 67 | pub struct Mask: u32 { 68 | /// An interrupt from the Graphics Synthesizer. 69 | const GS = 1; 70 | /// An interrupt from the SBUS connection to the IOP. 71 | const SBUS = 1 << 1; 72 | /// The start of VBlank. 73 | const VBON = 1 << 2; 74 | /// The end of VBlank. 75 | const VBOF = 1 << 3; 76 | /// An interrupt from VU Interface 0. 77 | const VIF0 = 1 << 4; 78 | /// An interrupt from VU Interface 1. 79 | const VIF1 = 1 << 5; 80 | /// An interrupt from Vector Unit 0. 81 | const VU0 = 1 << 6; 82 | /// An interrupt from Vector Unit 1. 83 | const VU1 = 1 << 7; 84 | /// An interrupt from the Image Processing Unit. 85 | const IPU = 1 << 8; 86 | /// An interrupt from Timer 0. 87 | const TIM0 = 1 << 9; 88 | /// An interrupt from Timer 1. 89 | const TIM1 = 1 << 10; 90 | /// An interrupt from Timer 2. 91 | const TIM2 = 1 << 11; 92 | /// An interrupt from Timer 3. 93 | const TIM3 = 1 << 12; 94 | /// An interrupt from the SBUS FIFO queue. 95 | const SFIFO = 1 << 13; 96 | /// An interrupt from the Vector Unit 0 watchdog. 97 | const VU0WD = 1 << 14; 98 | } 99 | } 100 | 101 | impl Mask { 102 | /// Load the interrupt controller mask. 103 | pub fn load() -> Self { 104 | let mask = unsafe { ptr::read_volatile(INTC_MASK) }; 105 | Mask { bits: mask } 106 | } 107 | 108 | /// Store the interrupt controller mask. 109 | pub fn store(self) { 110 | unsafe { ptr::write_volatile(INTC_MASK, self.bits) }; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /prussia_rt/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | 5 | asm-obj/ 6 | -------------------------------------------------------------------------------- /prussia_rt/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "prussia_rt" 3 | version = "0.4.2" 4 | license = "MIT OR Apache-2.0" 5 | authors = ["Dan Ravensloft "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | bitflags = "1.0.4" 10 | r0 = "0.2.2" 11 | -------------------------------------------------------------------------------- /prussia_rt/README.md: -------------------------------------------------------------------------------- 1 | # `prussia_rt` - startup and PS2-specific routines 2 | 3 | This crate contains startup routines to initialise the PS2 ready to hand over to your code. 4 | 5 | ## `main` 6 | `prussia_rt` expects your program's entry point to be like this: 7 | 8 | ```rust 9 | #[no_mangle] 10 | fn main() -> ! { 11 | // Your code here. 12 | } 13 | ``` 14 | 15 | I may later add a `cortex_m_rt`-style `entry!` macro or a `#[entry]` annotation. 16 | 17 | ## Interrupts 18 | `prussia_rt` provides `cortex_m`-style `interrupt::enable()`, `interrupt::disable` and 19 | `interrupt::free` functions to change the current interrupt status or call a closure in an 20 | interrupt-free context.` 21 | 22 | ## TODO: 23 | - Register access. 24 | - Coprocessor 0 register 25 | - Coprocessor 1 (FPU) control registers 26 | - Coprocessor 2 (VU0) control registers 27 | - EE kernel syscalls. 28 | - Threading, based on those syscalls? 29 | -------------------------------------------------------------------------------- /prussia_rt/build.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | env, 3 | error::Error, 4 | fs::{self, File}, 5 | io::Write, 6 | path::PathBuf, 7 | process::Command, 8 | }; 9 | 10 | const LIBPRUSSIA_RT_ASM_SRC_NAME: &str = "src/routines.S"; 11 | const LIBPRUSSIA_RT_ASM_LIB_NAME: &str = "libprussia-rt.a"; 12 | 13 | fn main() -> Result<(), Box> { 14 | // build directory for this crate 15 | let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); 16 | 17 | // extend the library search path 18 | println!("cargo:rustc-link-search={}", out_dir.display()); 19 | 20 | let libprussia_rt_asm_script_path = 21 | PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?).join("rebuild-asm-lib.sh"); 22 | 23 | // put `linkfile.ld` in the build directory 24 | File::create(out_dir.join("linkfile.ld"))?.write_all(include_bytes!("user-linkfile.ld"))?; 25 | 26 | // Rebuild if routines.S has changed. 27 | let libprussia_rt_asm_src_path = 28 | PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?).join(LIBPRUSSIA_RT_ASM_SRC_NAME); 29 | println!( 30 | "cargo:rerun-if-changed={}", 31 | libprussia_rt_asm_src_path.display() 32 | ); 33 | 34 | // Run the routines.S rebuild script. 35 | match Command::new(libprussia_rt_asm_script_path).status() { 36 | Ok(e) => { 37 | println!("rebuild-asm-lib.sh exit status: {e}"); 38 | } 39 | Err(e) => { 40 | return Err(Box::new(e)); 41 | } 42 | } 43 | 44 | // and put `libprussia-rt.a` in there too 45 | fs::copy( 46 | LIBPRUSSIA_RT_ASM_LIB_NAME, 47 | out_dir.join(LIBPRUSSIA_RT_ASM_LIB_NAME), 48 | )?; 49 | println!("cargo:rustc-link-lib=static=prussia-rt"); 50 | 51 | Ok(()) 52 | } 53 | -------------------------------------------------------------------------------- /prussia_rt/libprussia-rt.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ravenslofty/prussia/f7b3fe5c56b84c58785bc10496a5411d7f566755/prussia_rt/libprussia-rt.a -------------------------------------------------------------------------------- /prussia_rt/ps2.json: -------------------------------------------------------------------------------- 1 | ../ps2.json -------------------------------------------------------------------------------- /prussia_rt/rebuild-asm-lib.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # It doesn't need to target mips64el-none-elf, as long as it's mips64el. 4 | AS=mips64el-none-elf-as 5 | ASFLAGS="-march=r5900 -32 -KPIC -G0 -xgot" 6 | 7 | # Sanity check the given assembler 8 | # Does it exist? 9 | which $AS >/dev/null || echo "You do not have a MIPS assembler" 10 | 11 | # Is it MIPS? 12 | $AS --help | grep mips >/dev/null || echo "Your assembler does not support MIPS." 13 | 14 | # Is it MIPS R5900? 15 | $AS --help | grep r5900 >/dev/null || echo "Your assembler does not support the MIPS R5900" 16 | 17 | mkdir -p asm-obj 18 | rm asm-obj/* 19 | 20 | cd src 21 | find . -name "*.S" -exec $AS $ASFLAGS -o ../asm-obj/{}.o {} \; 22 | cd .. 23 | 24 | ar crs libprussia-rt.a asm-obj/*.o 25 | -------------------------------------------------------------------------------- /prussia_rt/src/atomic.rs: -------------------------------------------------------------------------------- 1 | //! Atomic reads and writes. 2 | 3 | use crate::interrupts; 4 | 5 | extern "C" { 6 | fn _read_u64(addr: usize) -> u64; 7 | fn _write_u64(addr: usize, value: u64); 8 | } 9 | 10 | /// Read a 64-bit value from an address. 11 | pub fn read_u64(addr: usize) -> u64 { 12 | let mut val = 0; 13 | interrupts::free(|| unsafe { 14 | val = _read_u64(addr); 15 | }); 16 | val 17 | } 18 | 19 | /// Write a 64-bit value to an address. 20 | pub fn write_u64(addr: usize, value: u64) { 21 | interrupts::free(|| unsafe { _write_u64(addr, value) }); 22 | } 23 | -------------------------------------------------------------------------------- /prussia_rt/src/cop0.rs: -------------------------------------------------------------------------------- 1 | //! Coprocessor 0 manipulation routines. 2 | 3 | use core::arch::{asm, global_asm}; 4 | 5 | use bitflags::bitflags; 6 | 7 | extern "C" { 8 | fn _read_badvaddr() -> u32; 9 | fn _read_timercount() -> u32; 10 | fn _write_timercount(count: u32); 11 | fn _read_compare() -> u32; 12 | fn _write_compare(compare: u32); 13 | fn _read_epc() -> u32; 14 | fn _write_epc(epc: u32); 15 | fn _read_badpaddr() -> u32; 16 | fn _write_badpaddr(badpaddr: u32); 17 | fn _read_errorepc() -> u32; 18 | fn _write_errorepc(errorepc: u32); 19 | fn _read_pccr() -> u32; 20 | fn _write_pccr(pccr: u32); 21 | fn _read_pcr0() -> u32; 22 | fn _read_pcr1() -> u32; 23 | fn _write_pcr0(pcr0: u32); 24 | fn _write_pcr1(pcr1: u32); 25 | } 26 | 27 | /// A virtual address responsible for either of the below exceptions: 28 | /// * TLB Invalid 29 | /// * TLB Modified 30 | /// * TLB Refill 31 | /// * Address Error 32 | #[derive(Debug)] 33 | pub struct BadVAddr(u32); 34 | 35 | impl BadVAddr { 36 | /// Load a [BadVAddr] from the _CoP0.BadVAddr_ register (`$12`) 37 | pub fn load() -> Self { 38 | let bad_v_addr = unsafe { _read_badvaddr() }; 39 | 40 | BadVAddr(bad_v_addr) 41 | } 42 | } 43 | 44 | /// A value read from the CoP0.Status register. The register increments every CPU clock cycle. 45 | /// This register, when equal to the CoP0.Compare register, signals a timer interrupt. 46 | /// FIXME: Pick a method, discard the other. 47 | #[derive(Debug)] 48 | pub struct TimerCount(u32); 49 | 50 | impl TimerCount { 51 | /// Load a [TimerCount] value from the _CoP0.Count_ register (`$9`). 52 | pub fn load() -> Self { 53 | let count = unsafe { _read_timercount() }; 54 | 55 | TimerCount(count) 56 | } 57 | 58 | /// Write [Self] to the _CoP0.Count_ register (`$9`). 59 | pub fn store(self) { 60 | unsafe { _write_timercount(self.0) } 61 | } 62 | } 63 | 64 | /// A value read from the CoP0.Compare register. The register acts as a timer; 65 | /// when the Count register becomes equal to the Compare register, the interrupt bit in the Cause 66 | /// register is set, and a timer interrupt occurs if enabled. 67 | #[derive(Debug)] 68 | pub struct Compare(u32); 69 | 70 | impl Compare { 71 | /// Load a [Compare] value from the _CoP0.Compare_ register (`$11`). 72 | pub fn load() -> Self { 73 | let compare = unsafe { _read_compare() }; 74 | 75 | Compare(compare) 76 | } 77 | 78 | /// Write [Self] to the _CoP0.Compare_ register (`$11`). 79 | pub fn store(self) { 80 | unsafe { _write_compare(self.0) } 81 | } 82 | } 83 | 84 | /// A value read from the CoP0.EPC register. The value is the returning virtual address to jump to 85 | /// after handling an exception. 86 | #[derive(Debug)] 87 | pub struct EPC(u32); 88 | 89 | impl EPC { 90 | /// Load an [EPC] value from the _CoP0.EPC_ register (`$14`). 91 | pub fn load() -> Self { 92 | let epc = unsafe { _read_epc() }; 93 | 94 | EPC(epc) 95 | } 96 | 97 | /// Write [Self] to the _CoP0.EPC_ register (`$14`). 98 | pub fn store(self) { 99 | unsafe { _write_epc(self.0) } 100 | } 101 | } 102 | 103 | /// A physical address read from the CoP0.BadPAddr register. The value is automatically set to the 104 | /// most recent physical address that caused a bus error (assuming bus error masking (Status.BEM) is disabled). 105 | #[derive(Debug)] 106 | pub struct BadPAddr(u32); 107 | 108 | impl BadPAddr { 109 | /// Load a [BadPAddr] value from the _CoP0.BadPAddr_ register (`$23`). 110 | pub fn load() -> Self { 111 | let badpaddr = unsafe { _read_badpaddr() }; 112 | 113 | BadPAddr(badpaddr) 114 | } 115 | 116 | /// Write [Self] to the _CoP0.BadPAddr_ register (`$23`). 117 | pub fn store(self) { 118 | unsafe { _write_badpaddr(self.0) } 119 | } 120 | } 121 | 122 | /// A virtual address read from the CoP0.ErrorEPC register. The value is a return address set when 123 | /// an NMI, debug, or counter exception occurs and is handled. The address normally points to the 124 | /// instruction which generated the error. If the instruction is in a branch delay slot, the address 125 | /// is set to the branch instruction prior to the erroring instruction (indicated by Cause.BD2 being set to 1). 126 | #[derive(Debug)] 127 | pub struct ErrorEPC(u32); 128 | 129 | impl ErrorEPC { 130 | /// Load an [ErrorEPC] value from _CoP0.ErrorEPC_ register (`$30`). 131 | pub fn load() -> Self { 132 | let errorepc = unsafe { _read_errorepc() }; 133 | 134 | ErrorEPC(errorepc) 135 | } 136 | 137 | /// Write [Self] to the _CoP0.ErrorEPC_ register (`$30`). 138 | pub fn store(self) { 139 | unsafe { _write_errorepc(self.0) } 140 | } 141 | } 142 | 143 | bitflags! { 144 | /// A value in the PCCR performance counter control register. 145 | pub struct PerfCounterControl: u32 { 146 | /// When set, enables a counting operation in CTR0 when handling a level 1 exception. 147 | const EXL0 = 1 << 1; 148 | /// When set, enables a counting operation in CTR0 in Kernel mode. 149 | const K0 = 1 << 2; 150 | /// When set, enables a counting operation in CTR0 in Supervisor mode. 151 | const S0 = 1 << 3; 152 | /// When set, enables a counting operation in CTR0 in User mode. 153 | const U0 = 1 << 4; 154 | /// The Id of the CTR0 events to be counted. 155 | const EVENT0 = 0x1F << 5; 156 | /// When set, enables a counting operation in CTR1 when handling a level 1 exception. 157 | const EXL1 = 1 << 11; 158 | /// When set, enables a counting operation in CTR1 in Kernel mode. 159 | const K1 = 1 << 12; 160 | /// When set, enables a counting operation in CTR1 in Supervisor mode. 161 | const S1 = 1 << 13; 162 | /// When set, enables a counting operation in CTR1 in User mode. 163 | const U1 = 1 << 14; 164 | /// The Id of the CTR1 events to be counted. 165 | const EVENT1 = 0x1F << 15; 166 | /// Enables the counter function. 167 | const CTE = 1 << 31; 168 | } 169 | } 170 | 171 | impl PerfCounterControl { 172 | /// Load a [PerfCounterControl] value from the _CoP0.PCCR_ register (via `mfps`). 173 | pub fn load() -> Self { 174 | let control = unsafe { _read_pccr() }; 175 | 176 | PerfCounterControl::from_bits_truncate(control) 177 | } 178 | 179 | /// Write [Self] to the _CoP0.PCCR_ register (via `mtps`). 180 | pub fn store(self) { 181 | let control = self.bits; 182 | unsafe { 183 | _write_pccr(control); 184 | } 185 | } 186 | } 187 | 188 | /// Represents the CTR0 event Ids supported by the PCCR.EVENT0 register field. 189 | #[derive(Debug)] 190 | #[repr(u8)] 191 | pub enum PCCREvent0 { 192 | /// Reserved 193 | Reserved = 0, 194 | /// Processor cycle 195 | ProcessorCycle = 1, 196 | /// Issues single instruction 197 | IssueSingleInstruction = 2, 198 | /// Issues branch 199 | IssuesBranch = 3, 200 | /// BTAC miss 201 | BtacMiss = 4, 202 | /// TLB miss 203 | TlbMiss = 5, 204 | /// Instruction cache (I$) miss 205 | InstructionCacheMiss = 6, 206 | /// Access DTLB 207 | AccessDtlb = 7, 208 | /// Non-blocking load 209 | NonBlockingLoad = 8, 210 | /// WBB single request 211 | WBBSingleRequest = 9, 212 | /// WBB burst request 213 | WBBBurstRequest = 10, 214 | /// CPU address bus busy 215 | CPUAddressBusBusy = 11, 216 | /// Completes instruction 217 | CompletesInstruction = 12, 218 | /// Completes non-BDS instruction 219 | CompletesNonBdsInstruction = 13, 220 | /// Completes COP2 instruction 221 | CompletesCop2Instruction = 14, 222 | /// Completes load 223 | CompletesLoads = 15, 224 | /// No event 225 | NoEvent = 16, 226 | } 227 | 228 | impl From for PerfCounterControl { 229 | fn from(value: PCCREvent0) -> Self { 230 | let event0 = (value as u32) << 5; 231 | 232 | PerfCounterControl::from_bits_truncate(event0) 233 | } 234 | } 235 | 236 | impl From for PCCREvent0 { 237 | fn from(value: PerfCounterControl) -> Self { 238 | let bits: u32 = (value & PerfCounterControl::EVENT0).bits >> 5; 239 | 240 | match bits { 241 | 0 => Self::Reserved, 242 | 1 => Self::ProcessorCycle, 243 | 2 => Self::IssueSingleInstruction, 244 | 3 => Self::IssuesBranch, 245 | 4 => Self::BtacMiss, 246 | 5 => Self::TlbMiss, 247 | 6 => Self::InstructionCacheMiss, 248 | 7 => Self::AccessDtlb, 249 | 8 => Self::NonBlockingLoad, 250 | 9 => Self::WBBSingleRequest, 251 | 10 => Self::WBBBurstRequest, 252 | 11 => Self::CPUAddressBusBusy, 253 | 12 => Self::CompletesInstruction, 254 | 13 => Self::CompletesNonBdsInstruction, 255 | 14 => Self::CompletesCop2Instruction, 256 | 15 => Self::CompletesLoads, 257 | 16 => Self::NoEvent, 258 | i if i > 16 && i < 32 => Self::Reserved, 259 | _ => Self::NoEvent, 260 | } 261 | } 262 | } 263 | 264 | /// Represents the CTR1 event Ids supported by the PCCR.EVENT1 register field. 265 | #[derive(Debug)] 266 | #[repr(u8)] 267 | pub enum PCCREvent1 { 268 | /// Issues low order branch 269 | IssuesLowOrderBranch = 0, 270 | /// Processor cycle 271 | ProcessorCycle = 1, 272 | /// Issues double instruction 273 | IssuesDoubleInstruction = 2, 274 | /// Branch prediction miss 275 | BranchPredictionMiss = 3, 276 | /// TLB miss 277 | TlbMiss = 4, 278 | /// DTLB miss 279 | DtlbMiss = 5, 280 | /// Data cache (D$) miss 281 | DataCacheMiss = 6, 282 | /// WBB single request unusable 283 | WbbSingleRequestUnusable = 7, 284 | /// WBB burst request unusable 285 | WbbBurstRequestUnusable = 8, 286 | /// WBB burst request almost full 287 | WbbBurstRequestAlmostFull = 9, 288 | /// WBB burst request full 289 | WbbBurstRequestFull = 10, 290 | /// CPU data bus busy 291 | CpuDataBusBusy = 11, 292 | /// Completes instruction 293 | CompletesInstruction = 12, 294 | /// Completes non-BDS instruction 295 | CompletesNonBdsInstruction = 13, 296 | /// Completes COP1 instruction 297 | CompletesCop1Instruction = 14, 298 | /// Completes stores 299 | CompletesStores = 15, 300 | /// No event 301 | NoEvent = 16, 302 | /// Reserved 303 | Reserved = 17, 304 | } 305 | 306 | impl From for PerfCounterControl { 307 | fn from(value: PCCREvent1) -> Self { 308 | let event1 = (value as u32) << 15; 309 | 310 | PerfCounterControl::from_bits_truncate(event1) 311 | } 312 | } 313 | 314 | impl From for PCCREvent1 { 315 | fn from(value: PerfCounterControl) -> Self { 316 | let bits: u32 = (value & PerfCounterControl::EVENT0).bits >> 5; 317 | 318 | match bits { 319 | 0 => Self::IssuesLowOrderBranch, 320 | 1 => Self::ProcessorCycle, 321 | 2 => Self::IssuesDoubleInstruction, 322 | 3 => Self::BranchPredictionMiss, 323 | 4 => Self::TlbMiss, 324 | 5 => Self::DtlbMiss, 325 | 6 => Self::DataCacheMiss, 326 | 7 => Self::WbbSingleRequestUnusable, 327 | 8 => Self::WbbBurstRequestUnusable, 328 | 9 => Self::WbbBurstRequestAlmostFull, 329 | 10 => Self::WbbBurstRequestFull, 330 | 11 => Self::CpuDataBusBusy, 331 | 12 => Self::CompletesInstruction, 332 | 13 => Self::CompletesNonBdsInstruction, 333 | 14 => Self::CompletesCop1Instruction, 334 | 15 => Self::CompletesStores, 335 | 16 => Self::NoEvent, 336 | i if i > 16 && i < 32 => Self::Reserved, 337 | _ => Self::NoEvent, 338 | } 339 | } 340 | } 341 | 342 | /// Represents a value from the _Cop0.PCR0/1_ Performance Counter registers. 343 | #[derive(Debug)] 344 | #[repr(transparent)] 345 | pub struct PerfCounter(u32); 346 | 347 | impl PerfCounter { 348 | /// Mask for the OVFL bit. 349 | pub const OVFL: u32 = 1 << 31; 350 | /// Mask for the VALUE field. 351 | pub const VALUE: u32 = u32::MAX >> 1; 352 | 353 | /// Check if the OVFL bit is enabled. 354 | #[inline(always)] 355 | pub fn is_ovfl(&self) -> bool { 356 | self.0 & Self::OVFL == 1 357 | } 358 | 359 | /// Get the contents of the VALUE field. 360 | #[inline(always)] 361 | pub fn value(&self) -> u32 { 362 | self.0 & Self::VALUE 363 | } 364 | 365 | /// Load a [PerfCounter] value from the _CoP0.PCR0_ register (via `mfpc`). 366 | pub fn load_pcr0() -> Self { 367 | let pcr0 = unsafe { _read_pcr0() }; 368 | 369 | PerfCounter(pcr0) 370 | } 371 | 372 | /// Load a [PerfCounter] value from the _CoP0.PCR1_ register (via `mfpc`). 373 | pub fn load_pcr1() -> Self { 374 | let pcr1 = unsafe { _read_pcr1() }; 375 | 376 | PerfCounter(pcr1) 377 | } 378 | 379 | /// Write [Self] to the _CoP0.PCR0_ register (via `mtpc`). 380 | pub fn store_pcr0(self) { 381 | unsafe { _write_pcr0(self.0) } 382 | } 383 | 384 | /// Write [Self] to the _CoP0.PCR1_ register (via `mtpc`). 385 | pub fn store_pcr1(self) { 386 | unsafe { _write_pcr1(self.0) } 387 | } 388 | } 389 | 390 | bitflags! { 391 | /// The current processor state. 392 | pub struct Status: u32 { 393 | /// Whether interrupts are enabled. 0 = masked, 1 = enabled. 394 | const IE = 1; 395 | /// Whether we are in an exception (everything which isn't an error) context. 396 | const EXL = 1 << 1; 397 | /// Whether we are in an error (Reset, NMI, performance counter, debug exception) context. 398 | const ERL = 1 << 2; 399 | /// Which processor mode we are in. 00 = kernel, 01 = supervisor, 10 = user. 400 | const KSU = 3 << 3; 401 | /// Whether interrupt 2 is masked. 0 = masked, 1 = enabled. 402 | const IM2 = 1 << 10; 403 | /// Whether interrupt 3 is masked. 0 = masked, 1 = enabled. 404 | const IM3 = 1 << 11; 405 | /// Whether bus errors are masked. 0 = masked, 1 = enabled. 406 | const BEM = 1 << 12; 407 | /// Whether interrupt 7 is masked. 0 = masked, 1 = enabled. 408 | const IM7 = 1 << 15; 409 | /// Whether the IE bit is enabled. 0 = disabled (this disables all interrupts), 1 = enabled. 410 | const EIE = 1 << 16; 411 | /// Whether the EI/DI instructions have any effect in user mode. 412 | /// 0 = no effect in user mode, 1 = normal function in user mode. 413 | const EDI = 1 << 17; 414 | /// Status of the last CACHE instruction. 0 = miss, 1 = hit. 415 | const CH = 1 << 18; 416 | /// Whether TLB or general exception handlers are located in RAM or ROM. 0 = RAM, 1 = ROM. 417 | const BEV = 1 << 22; 418 | /// Whether performance counter/debug exceptions are located in RAM or ROM. 419 | /// 0 = RAM, 1 = ROM. 420 | const DEV = 1 << 23; 421 | /// Whether coprocessor 0 is usable. 0 = unusable, 1 = usable. 422 | const CU0 = 1 << 28; 423 | /// Whether coprocessor 1 is usable. 0 = unusable, 1 = usable. 424 | const CU1 = 1 << 29; 425 | /// Whether coprocessor 2 is usable. 0 = unusable, 1 = usable. 426 | const CU2 = 1 << 30; 427 | /// Whether coprocessor 3 is usable. 0 = unusable, 1 = usable. 428 | const CU3 = 1 << 31; 429 | } 430 | } 431 | 432 | impl Status { 433 | /// Load the contents of the Coprocessor 0 Status register, returning a Status type with the 434 | /// value of Status. 435 | pub fn load() -> Self { 436 | let status; 437 | unsafe { asm!(".set noat; mfc0 {}, $12", out(reg) status) }; 438 | 439 | Status { bits: status } 440 | } 441 | 442 | /// Store this object to the Coprocessor 0 Status register. 443 | pub fn store(self) { 444 | unsafe { asm!("mtc0 {}, $12", in(reg) self.bits) }; 445 | } 446 | } 447 | 448 | bitflags! { 449 | /// Cause of the most recent exception. 450 | pub struct Cause: u32 { 451 | /// Level 1 exception code. 452 | const EXC_CODE = 0x1F << 2; 453 | /// Interrupt from the Interrupt Controller is pending. 454 | const IP2 = 1 << 10; 455 | /// Interrupt from the DMA Controller is pending. 456 | const IP3 = 1 << 11; 457 | /// Interrupt from the timer is pending. 458 | const IP7 = 1 << 15; 459 | /// Level 2 exception code. 460 | const EXC2 = 0x7 << 16; 461 | /// Coprocessor number of a Coprocessor Unusable exception. 462 | const CE = 0x3 << 28; 463 | /// Level 2 exception occurred in a branch delay slot. 464 | const BD2 = 1 << 30; 465 | /// Level 1 exception occurred in a branch delay slot. 466 | const BD = 1 << 31; 467 | } 468 | } 469 | 470 | impl Cause { 471 | /// Load the contents of the Coprocessor 0 Cause register, returning a Cause type with the 472 | /// value of Cause. 473 | pub fn load() -> Self { 474 | let cause; 475 | unsafe { asm!(".set noat; mfc0 {}, $13", out(reg) cause) }; 476 | 477 | Cause { bits: cause } 478 | } 479 | } 480 | 481 | /// Level 1 exception types. 482 | #[derive(Debug)] 483 | pub enum L1Exception { 484 | /// An interrupt occurred. 485 | Interrupt, 486 | /// A TLB page marked not Dirty (not writable) was written to. 487 | TlbModified, 488 | /// No TLB entry was found while loading data or instructions from memory. 489 | TlbMissLoad, 490 | /// No TLB entry was found while storing data to memory. 491 | TlbMissStore, 492 | /// A TLB page marked not Valid (not mapped) was read from. 493 | TlbInvalidLoad, 494 | /// A TLB page marked not Valid (not mapped) was written to. 495 | TlbInvalidStore, 496 | /// An address error occurred while loading data or instructions from memory. 497 | AddrErrLoad, 498 | /// An address error occurred while storing data to memory. 499 | AddrErrStore, 500 | /// A bus error occurred while loading instructions. 501 | InsnBusError, 502 | /// A bus error occurred while loading/storing data. 503 | DataBusError, 504 | /// A system call was made. 505 | SystemCall, 506 | /// A debug breakpoint was executed. 507 | Breakpoint, 508 | /// An unrecognised instruction was executed. 509 | ReservedInsn, 510 | /// A coprocessor marked as unusable was used. 511 | CoprocessorUnusable, 512 | /// Two's complement arithmetic overflow occurred. 513 | Overflow, 514 | /// A trap instruction was executed. 515 | Trap, 516 | } 517 | 518 | impl L1Exception { 519 | /// Convert a L1 exception code in the TLB Miss exception handler. 520 | /// This function returns Option, but if it fails, you're passing in the wrong value. 521 | pub fn try_from_tlbmiss(x: u8) -> Option { 522 | match x { 523 | 2 => Some(L1Exception::TlbMissLoad), 524 | 3 => Some(L1Exception::TlbMissStore), 525 | _ => None, 526 | } 527 | } 528 | 529 | /// Convert a L1 exception code in the Common exception handler. 530 | /// This function rturns Option, but if it fails, you're passing in the wrong value. 531 | pub fn try_from_common(x: u8) -> Option { 532 | match x { 533 | 1 => Some(L1Exception::TlbModified), 534 | 2 => Some(L1Exception::TlbInvalidLoad), 535 | 3 => Some(L1Exception::TlbInvalidStore), 536 | 4 => Some(L1Exception::AddrErrLoad), 537 | 5 => Some(L1Exception::AddrErrStore), 538 | 6 => Some(L1Exception::InsnBusError), 539 | 7 => Some(L1Exception::DataBusError), 540 | 8 => Some(L1Exception::SystemCall), 541 | 9 => Some(L1Exception::Breakpoint), 542 | 10 => Some(L1Exception::ReservedInsn), 543 | 11 => Some(L1Exception::CoprocessorUnusable), 544 | 12 => Some(L1Exception::Overflow), 545 | 13 => Some(L1Exception::Trap), 546 | _ => None, 547 | } 548 | } 549 | } 550 | 551 | /// Level 2 exception types. 552 | #[derive(Debug)] 553 | pub enum L2Exception { 554 | /// The processor was reset. 555 | Reset, 556 | /// A non-maskable interrupt occurred. 557 | NMI, 558 | /// The performance counter overflowed. 559 | PerfCounter, 560 | /// A breakpoint condition occurred. 561 | Debug, 562 | } 563 | 564 | impl L2Exception { 565 | /// Convert a level 2 exception code in the Reset handler. 566 | pub fn try_from_reset(x: u8) -> Option { 567 | match x { 568 | 0 => Some(L2Exception::Reset), 569 | 1 => Some(L2Exception::NMI), 570 | _ => None, 571 | } 572 | } 573 | 574 | /// Convert a level 2 exception code in the Performance Counter handler. 575 | pub fn try_from_counter(x: u8) -> Option { 576 | match x { 577 | 2 => Some(L2Exception::PerfCounter), 578 | _ => None, 579 | } 580 | } 581 | 582 | /// Convert a level 2 exception code in the Debug handler. 583 | pub fn try_from_debug(x: u8) -> Option { 584 | match x { 585 | 4 => Some(L2Exception::Debug), 586 | _ => None, 587 | } 588 | } 589 | } 590 | -------------------------------------------------------------------------------- /prussia_rt/src/interrupts.rs: -------------------------------------------------------------------------------- 1 | //! Interrupt handling and management. 2 | #![allow(dead_code)] 3 | 4 | use crate::cop0; 5 | 6 | /// Disable interrupts. 7 | pub fn disable() { 8 | // By not using the `di` instruction, we sidestep the hardware errata. 9 | let mut status = cop0::Status::load(); 10 | status.remove(cop0::Status::EIE); // `di`/`ei` use the EIE bit, rather than IE. 11 | status.remove(cop0::Status::IE); 12 | status.store(); 13 | } 14 | 15 | /// Whether interrupts are enabled or disabled. 16 | pub enum Status { 17 | /// Interrupts are disabled. 18 | Disabled, 19 | /// Interrupts are enabled. 20 | Enabled, 21 | } 22 | 23 | /// Get current interrupt status. 24 | pub fn status() -> Status { 25 | let status = cop0::Status::load(); 26 | if status.contains(cop0::Status::IE) && status.contains(cop0::Status::EIE) { 27 | Status::Enabled 28 | } else { 29 | Status::Disabled 30 | } 31 | } 32 | 33 | /// Enable interrupts. 34 | pub fn enable() { 35 | let mut status = cop0::Status::load(); 36 | status.insert(cop0::Status::EIE); 37 | status.insert(cop0::Status::IE); 38 | status.store(); 39 | } 40 | 41 | /// Execute a closure in an interrupt-free context, preserving previous interrupt state. 42 | pub fn free(f: T) { 43 | match status() { 44 | Status::Enabled => { 45 | disable(); 46 | f(); 47 | enable(); 48 | } 49 | Status::Disabled => { 50 | f(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /prussia_rt/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Startup / runtime for the Sony PlayStation 2. 2 | //! 3 | //! This crate provides routines to bootstrap a Rust environment for the PS2. 4 | //! 5 | //! Your main function needs to have the following declaration: 6 | //! ``` 7 | //! #[no_mangle] 8 | //! fn main() -> !; 9 | //! ``` 10 | 11 | #![no_std] 12 | #![deny(missing_docs)] 13 | #![feature(asm_experimental_arch)] 14 | 15 | pub mod atomic; 16 | pub mod cop0; 17 | pub mod interrupts; 18 | 19 | // Static data initialised to zero goes in the .bss segment, which is essentially a pointer to 20 | // uninitialised memory. We need to zero .bss before the main program runs. 21 | // 22 | // This could be done in assembly (and is in PS2SDK), but I figured this was not speed-critical. 23 | unsafe fn zero_bss() { 24 | // Due to a quirk of the linker, these symbols are given addresses, but there is no space 25 | // allocated for them. Instead the addresses *are* the values, in this case referring to the 26 | // start and end of .bss. 27 | extern "C" { 28 | static mut START_OF_BSS: u32; 29 | static mut END_OF_BSS: u32; 30 | } 31 | 32 | r0::zero_bss::(&mut START_OF_BSS as *mut u32, &mut END_OF_BSS as *mut u32); 33 | } 34 | 35 | // A PS2 program's execution flow begins in _start, which calls the EE kernel to set up this thread 36 | // and then calls _rust_start. Our job here is to provide a safe Rust startup and then call main(). 37 | #[doc(hidden)] 38 | #[no_mangle] 39 | pub unsafe extern "C" fn _rust_start() -> ! { 40 | extern "Rust" { 41 | fn main() -> !; 42 | } 43 | 44 | zero_bss(); 45 | 46 | main() 47 | } 48 | -------------------------------------------------------------------------------- /prussia_rt/src/routines.S: -------------------------------------------------------------------------------- 1 | # The assembler tries to reorder our instructions around delay slots. 2 | # Since we want to preserve this order, disable the reordering feature. 3 | .set noreorder 4 | 5 | # Bootstrap routine for PruSSia. LLVM only needs a stack pointer, and the rest we can do in Rust. 6 | .extern _rust_start 7 | .global _start 8 | _start: 9 | j _rust_start # Call Rust 10 | lui $sp, 0x20 # Set the stack pointer to 0x0020'0000. 11 | 12 | # Read coprocessor 0 Status register. This *could* be done with inline assembly, but I'm going to 13 | # aim for compilation on stable. 14 | .global _read_status 15 | _read_status: 16 | jr $ra # Return to Rust... 17 | mfc0 $2, $12 # with the Status register value. 18 | 19 | # Write coprocessor 0 Status register. 20 | # $4 (a0) = value. 21 | .global _write_status 22 | _write_status: 23 | jr $ra # Return to Rust... 24 | mtc0 $4, $12 # after setting the Status register. 25 | 26 | # Read coprocessor 0 BadVAddr register. 27 | .global _read_badvaddr 28 | _read_badvaddr: 29 | jr $ra 30 | mfc0 $2, $8 31 | 32 | # Read coprocessor 0 Count register. 33 | .global _read_timercount 34 | _read_timercount: 35 | jr $ra 36 | mfc0 $2, $9 37 | 38 | # Write coprocessor 0 Count register. 39 | .global _write_timercount 40 | _write_timercount: 41 | jr $ra 42 | mtc0 $4, $9 43 | 44 | # Read coprocessor 0 Compare register. 45 | .global _read_compare 46 | _read_compare: 47 | jr $ra 48 | mfc0 $2, $11 49 | 50 | # Write coprocessor 0 Compare register. 51 | .global _write_compare 52 | _write_compare: 53 | jr $ra 54 | mtc0 $4, $11 55 | 56 | # Read coprocessor 0 EPC register. 57 | .global _read_epc 58 | _read_epc: 59 | jr $ra 60 | mfc0 $2, $14 61 | 62 | # Write coprocessor 0 EPC register. 63 | .global _write_epc 64 | _write_epc: 65 | jr $ra 66 | mtc0 $4, $14 67 | 68 | # Read coprocessor 0 BadPAddr register. 69 | .global _read_badpaddr 70 | _read_badpaddr: 71 | jr $ra 72 | mfc0 $2, $23 73 | 74 | # Write coprocessor 0 BadPAddr register. 75 | .global _write_badpaddr 76 | _write_badpaddr: 77 | jr $ra 78 | mtc0 $4, $23 79 | 80 | # Read coprocessor 0 ErrorEPC register. 81 | .global _read_errorepc 82 | _read_errorepc: 83 | jr $ra 84 | mfc0 $2, $30 85 | 86 | # Write coprocessor 0 ErrorEPC register. 87 | .global _write_errorepc 88 | _write_errorepc: 89 | jr $ra 90 | mtc0 $4, $30 91 | 92 | # Read coprocessor 0 Perf/PCCR register. 93 | .global _read_pccr 94 | _read_pccr: 95 | jr $ra 96 | mfps $2, 0 97 | 98 | # Write coprocessor 0 Perf/PCCR register. 99 | .global _write_pccr 100 | _write_pccr: 101 | jr $ra 102 | mtps $4, 0 103 | 104 | # Read coprocessor 0 PCR0 register. 105 | .global _read_pcr0 106 | _read_pcr0: 107 | jr $ra 108 | mfpc $2, 0 109 | 110 | # Write coprocessor 0 PCR0 register. 111 | .global _write_pcr0 112 | _write_pcr0: 113 | jr $ra 114 | mtpc $4, 0 115 | 116 | # Read coprocessor 1 PCR1 register. 117 | .global _read_pcr1 118 | _read_pcr1: 119 | jr $ra 120 | mfpc $2, 1 121 | 122 | # Write coprocessor 1 PCR1 register. 123 | .global _write_pcr1 124 | _write_pcr1: 125 | jr $ra 126 | mtpc $4, 1 127 | 128 | 129 | # Read a u64 atomically. Rust would make two reads, but this would just be the truncated bottom 130 | # half. This method is always correct though. 131 | # $4 (a0) = address. 132 | .global _read_u64 133 | _read_u64: 134 | nor $8, $0, $0 # Create a 64-bit all-ones mask in $t0. 135 | dsrl32 $8, 0 # Turn it into 32-bit. 136 | ld $2, 0($4) # Load from memory into $v0. 137 | move $3, $2 # Copy into $v1. 138 | and $2, $8 # Return lowest word in $v0. 139 | dsrl32 $3, 0 # Return highest word in $v1. 140 | jr $ra # And return to caller. 141 | nop 142 | 143 | # Write a u64 atomically. Rust would make two writes, but this would probably confuse the device 144 | # we are writing to. This method is always correct though. 145 | # $4 (a0) = address. 146 | # $5 (a1) = value (lower 32 bits). 147 | # $6 (a2) = value (upper 32 bits). 148 | .global _write_u64 149 | _write_u64: 150 | dsll32 $6, 0 # upper <<= 32 151 | or $5, $6 # lower |= upper 152 | jr $ra 153 | sd $6, 0($4) # *address = lower 154 | -------------------------------------------------------------------------------- /prussia_rt/user-linkfile.ld: -------------------------------------------------------------------------------- 1 | /* We need the linker to start executing code from _start to bring up the Rust runtime before Rust runs */ 2 | ENTRY(_start); 3 | EXTERN(_start); 4 | 5 | SECTIONS { 6 | /* The .text segment contains the executable machine code. 7 | * PS2 programs must load at 0x0010'0000 or higher, because the EE kernel reserves the first megabyte 8 | * of memory for internal use. 9 | */ 10 | .text 0x00100000: { 11 | *(.text .text.*); 12 | } 13 | 14 | /* The .data segment contains mutable globals initialised with a non-zero value. */ 15 | .sdata ALIGN(128) : { 16 | *(.sdata .sdata.*); 17 | } 18 | 19 | .data ALIGN(128) : { 20 | *(.data .data.*); 21 | } 22 | 23 | /* The .rodata segment contains constant globals. */ 24 | .rodata ALIGN(128) : { 25 | *(.rodata .rodata.*); 26 | } 27 | 28 | /* The .bss segment contains mutable globals initialised with a zero value. */ 29 | .sbss ALIGN(128) : { 30 | START_OF_BSS = .; 31 | *(.sbss .sbss.*); 32 | } 33 | 34 | .bss ALIGN(128) : { 35 | *(.bss .bss.*); 36 | END_OF_BSS = .; 37 | } 38 | 39 | PROVIDE(END_OF_RAM = 0x02000000); 40 | } 41 | -------------------------------------------------------------------------------- /ps2.json: -------------------------------------------------------------------------------- 1 | { 2 | "arch": "mips", 3 | "cpu": "mips2", 4 | "data-layout": "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64", 5 | "executables": true, 6 | "features": "+mips2,+soft-float", 7 | "is-builtin": false, 8 | "linker": "mips64el-none-elf-ld", 9 | "linker-flavor": "ld", 10 | "llvm-target": "mipsel-none-elf", 11 | "max-atomic-width": 32, 12 | "os": "none", 13 | "panic-strategy": "abort", 14 | "position-independent-executables": false, 15 | "relro-level": "full", 16 | "target-c-int-width": "32", 17 | "target-endian": "little", 18 | "target-pointer-width": "32", 19 | "vendor": "unknown", 20 | "post-link-args": { 21 | "ld": ["-Tlinkfile.ld"] 22 | }, 23 | "relocation-model": "static" 24 | } 25 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly" 3 | components = ["rust-std", "rust-src"] --------------------------------------------------------------------------------