diff options
author | Andrew Walbran <qwandor@google.com> | 2023-05-31 09:04:59 +0000 |
---|---|---|
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | 2023-05-31 09:04:59 +0000 |
commit | c0aeb8d805e2dfb991c1998a92b720d12a4efded (patch) | |
tree | 87fa9cb85f2b085c42aa0598ddfa0ac75b1c8a18 | |
parent | 0468cef0e9296a449e2513b28f086c0172842334 (diff) | |
parent | e1acccb6f09bf723b33aa7f360a419bd9335d71d (diff) | |
download | smccc-c0aeb8d805e2dfb991c1998a92b720d12a4efded.tar.gz |
Initial import. am: f339508ca1 am: d3ba65cbc7 am: a8c20effde am: f13bd30f9b am: e1acccb6f0
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/smccc/+/2607186
Change-Id: I83acff0bf7b31f25281a77438376cbb69cdcab1d
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
-rw-r--r-- | .cargo_vcs_info.json | 6 | ||||
-rw-r--r-- | .github/workflows/rust.yml | 30 | ||||
-rw-r--r-- | .gitignore | 2 | ||||
-rw-r--r-- | AUTHORS | 7 | ||||
-rw-r--r-- | Android.bp | 36 | ||||
-rw-r--r-- | CHANGELOG.md | 42 | ||||
-rw-r--r-- | CONTRIBUTING.md | 26 | ||||
-rw-r--r-- | Cargo.toml | 37 | ||||
-rw-r--r-- | Cargo.toml.orig | 15 | ||||
-rw-r--r-- | LICENSE | 229 | ||||
-rw-r--r-- | LICENSE-APACHE | 202 | ||||
-rw-r--r-- | LICENSE-MIT | 21 | ||||
-rw-r--r-- | METADATA | 20 | ||||
-rw-r--r-- | MODULE_LICENSE_APACHE2 | 0 | ||||
-rw-r--r-- | OWNERS | 1 | ||||
-rw-r--r-- | README.md | 32 | ||||
-rw-r--r-- | cargo2android.json | 9 | ||||
-rw-r--r-- | patches/Android.bp.patch | 17 | ||||
-rw-r--r-- | rust-toolchain.toml | 2 | ||||
-rw-r--r-- | src/arch.rs | 88 | ||||
-rw-r--r-- | src/arch/calls.rs | 43 | ||||
-rw-r--r-- | src/arch/error.rs | 58 | ||||
-rw-r--r-- | src/error.rs | 78 | ||||
-rw-r--r-- | src/lib.rs | 172 | ||||
-rw-r--r-- | src/psci.rs | 166 | ||||
-rw-r--r-- | src/psci/calls.rs | 354 | ||||
-rw-r--r-- | src/psci/error.rs | 104 |
27 files changed, 1797 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..bf3f15a --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "6a7e96faf4a0e1a0ef72d0c3993d8c5902df13b8" + }, + "path_in_vcs": "" +}
\ No newline at end of file diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 0000000..0aa1a63 --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,30 @@ +name: Rust + +on: + push: + branches: [main] + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Build + run: cargo build + - name: Run tests + run: cargo test + - name: Run clippy + uses: actions-rs/clippy-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Format Rust code + run: cargo fmt --all -- --check diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..81cf465 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +/.vscode @@ -0,0 +1,7 @@ +# This is the list of smccc's significant contributors. +# +# This does not necessarily list everyone who has contributed code, +# especially since many employees of one corporation may be contributing. +# To see the full list of contributors, see the revision history in +# source control. +Google LLC diff --git a/Android.bp b/Android.bp new file mode 100644 index 0000000..5ce080e --- /dev/null +++ b/Android.bp @@ -0,0 +1,36 @@ +// This file is generated by cargo2android.py --config cargo2android.json. +// Do not modify this file as changes will be overridden on upgrade. + + + +rust_library_rlib { + name: "libsmccc", + crate_name: "smccc", + cargo_env_compat: true, + cargo_pkg_version: "0.1.1", + srcs: ["src/lib.rs"], + edition: "2021", + apex_available: [ + "//apex_available:platform", + "//apex_available:anyapex", + ], + product_available: true, + vendor_available: true, + prefer_rlib: true, + no_stdlibs: true, + stdlibs: [ + "libcompiler_builtins.rust_sysroot", + "libcore.rust_sysroot", + ], +} + +rust_test { + name: "smccc_test_src_lib", + crate_name: "smccc", + cargo_env_compat: true, + cargo_pkg_version: "0.1.1", + srcs: ["src/lib.rs"], + test_suites: ["general-tests"], + auto_gen_config: true, + edition: "2021", +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d7d52e7 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +## 0.1.1 + +### Bugfixes + +- Fixed docs.rs to build for aarch64. + +## 0.1.0 + +Renamed crate to `smccc`. + +### Breaking changes + +- Moved PSCI code to the `psci` module, moved other modules up one level. +- Use type parameters rather than features to specify HVC vs. SMC for PSCI and arch calls. +- Changed `error::Error::Unknown` to contain an `i64` rather than an `i32`. + +## `psci` 0.1.3 + +### Bugfixes + +- Fixed type of `smccc::error::success_or_error_64`. This is a breaking change relative to 0.1.2 but + it was yanked. + +## `psci` 0.1.2 (yanked) + +### New features + +- Added constants, types and functions for standard Arm architucture SMCCC calls, in `smccc::arch` + module. +- Added helpers in `smccc::error` module for handling negative return values as errors. + +## `psci` 0.1.1 + +### New features + +- Exposed functions for SMC and HVC calls for use outside of PSCI. + +## `psci` 0.1.0 + +Initial release with PSCI constants and functions. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c88469f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are just a few small +guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License Agreement (CLA). You (or +your employer) retain the copyright to your contribution; this simply gives us permission to use and +redistribute your contributions as part of the project. Head over to +<https://cla.developers.google.com/> to see your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one (even if it was for +a different project), you probably don't need to do it again. + +## Code Reviews + +All submissions, including submissions by project members, require review. We use GitHub pull +requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using +pull requests. + +## Community Guidelines + +This project follows +[Google's Open Source Community Guidelines](https://opensource.google/conduct/). diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..795596d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,37 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "smccc" +version = "0.1.1" +authors = ["Andrew Walbran <qwandor@google.com>"] +description = "Functions and constants for the Arm SMC Calling Convention (SMCCC) 1.4 and Arm Power State Coordination Interface (PSCI) 1.1 on aarch64." +readme = "README.md" +keywords = [ + "arm", + "aarch64", + "cortex-a", + "smccc", + "psci", +] +categories = [ + "embedded", + "no-std", + "hardware-support", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/google/smccc" + +[package.metadata.docs.rs] +default-target = "aarch64-unknown-none" + +[dependencies] diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..8965a79 --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,15 @@ +[package] +name = "smccc" +version = "0.1.1" +edition = "2021" +license = "MIT OR Apache-2.0" +description = "Functions and constants for the Arm SMC Calling Convention (SMCCC) 1.4 and Arm Power State Coordination Interface (PSCI) 1.1 on aarch64." +authors = ["Andrew Walbran <qwandor@google.com>"] +repository = "https://github.com/google/smccc" +keywords = ["arm", "aarch64", "cortex-a", "smccc", "psci"] +categories = ["embedded", "no-std", "hardware-support"] + +[dependencies] + +[package.metadata.docs.rs] +default-target = "aarch64-unknown-none" @@ -0,0 +1,229 @@ +This project is dual-licensed under Apache 2.0 and MIT terms. + +==== + +MIT License + +Copyright (c) 2020 The cloudbbq authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +==== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..e5fc1d8 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 The cloudbbq authors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/METADATA b/METADATA new file mode 100644 index 0000000..c4d7f0b --- /dev/null +++ b/METADATA @@ -0,0 +1,20 @@ +name: "smccc" +description: "Functions and constants for the Arm SMC Calling Convention (SMCCC) 1.4 and Arm Power State Coordination Interface (PSCI) 1.1 on aarch64." +third_party { + url { + type: HOMEPAGE + value: "https://crates.io/crates/smccc" + } + url { + type: ARCHIVE + value: "https://static.crates.io/crates/smccc/smccc-0.1.1.crate" + } + version: "0.1.1" + # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same. + license_type: NOTICE + last_upgrade_date { + year: 2023 + month: 5 + day: 10 + } +} diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2 new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/MODULE_LICENSE_APACHE2 @@ -0,0 +1 @@ +include platform/prebuilts/rust:master:/OWNERS diff --git a/README.md b/README.md new file mode 100644 index 0000000..4d8af68 --- /dev/null +++ b/README.md @@ -0,0 +1,32 @@ +# SMCCC and PSCI functions for bare-metal Rust on aarch64 + +[![crates.io page](https://img.shields.io/crates/v/smccc.svg)](https://crates.io/crates/smccc) +[![docs.rs page](https://docs.rs/smccc/badge.svg)](https://docs.rs/smccc) + +This crate provides support for the Arm SMC Calling Convention version 1.4, including standard Arm +Architecture Calls constants, and version 1.1 of the Arm Power State Coordination Interface (PSCI). +It includes constants, functions to make the calls (on aarch64 targets), and error types. + +Note that the PSCI and SMCCC arch calls may be made via either HVC or SMC. You can choose which one +to use by passing either `Hvc` or `Smc` as a type parameter to the relevant function. + +This crate currently only supports aarch64 and the SMC64 versions of the PSCI calls, in the cases +that both SMC32 and SMC64 versions exist. + +This is not an officially supported Google product. + +## License + +Licensed under either of + +- Apache License, Version 2.0 + ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) +- MIT license + ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +## Contributing + +If you want to contribute to the project, see details of +[how we accept contributions](CONTRIBUTING.md). diff --git a/cargo2android.json b/cargo2android.json new file mode 100644 index 0000000..c402bab --- /dev/null +++ b/cargo2android.json @@ -0,0 +1,9 @@ +{ + "dependencies": true, + "device": true, + "force-rlib": true, + "no-host": true, + "patch": "patches/Android.bp.patch", + "run": true, + "tests": true +} diff --git a/patches/Android.bp.patch b/patches/Android.bp.patch new file mode 100644 index 0000000..1fa0e93 --- /dev/null +++ b/patches/Android.bp.patch @@ -0,0 +1,17 @@ +diff --git a/Android.bp b/Android.bp +index 34d110a..2348c03 100644 +--- a/Android.bp ++++ b/Android.bp +@@ -53,6 +53,12 @@ rust_library_rlib { + ], + product_available: true, + vendor_available: true, ++ prefer_rlib: true, ++ no_stdlibs: true, ++ stdlibs: [ ++ "libcompiler_builtins.rust_sysroot", ++ "libcore.rust_sysroot", ++ ], + } + + rust_test { diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..3bd233d --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +targets = ["aarch64-unknown-none"] diff --git a/src/arch.rs b/src/arch.rs new file mode 100644 index 0000000..e3673f7 --- /dev/null +++ b/src/arch.rs @@ -0,0 +1,88 @@ +// Copyright 2023 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +//! Standard Arm architecture calls. + +mod calls; +pub mod error; + +pub use calls::{ + arch_workaround_1, arch_workaround_2, arch_workaround_3, features, soc_id, version, +}; +use core::fmt::{self, Debug, Display, Formatter}; +pub use error::Error; + +pub const SMCCC_VERSION: u32 = 0x8000_0000; +pub const SMCCC_ARCH_FEATURES: u32 = 0x8000_0001; +pub const SMCCC_ARCH_SOC_ID: u32 = 0x8000_0002; +pub const SMCCC_ARCH_WORKAROUND_1: u32 = 0x8000_8000; +pub const SMCCC_ARCH_WORKAROUND_2: u32 = 0x8000_7FFF; +pub const SMCCC_ARCH_WORKAROUND_3: u32 = 0x8000_3FFF; + +/// A version of the SMC Calling Convention. +#[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd)] +pub struct Version { + pub major: u16, + pub minor: u16, +} + +impl Display for Version { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "{}.{}", self.major, self.minor) + } +} + +impl Debug for Version { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + Display::fmt(self, f) + } +} + +impl TryFrom<i32> for Version { + type Error = Error; + + fn try_from(value: i32) -> Result<Self, Error> { + if value < 0 { + Err(value.into()) + } else { + Ok(Self { + major: (value >> 16) as u16, + minor: value as u16, + }) + } + } +} + +impl From<Version> for u32 { + fn from(version: Version) -> Self { + u32::from(version.major) << 16 | u32::from(version.minor) + } +} + +#[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd)] +#[repr(u32)] +pub enum SocIdType { + /// The SoC version. + Version, + /// The SoC revision. + Revision, +} + +impl From<SocIdType> for u32 { + fn from(id_type: SocIdType) -> Self { + id_type as Self + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn convert_version() { + let version = Version { major: 1, minor: 2 }; + assert_eq!(u32::from(version), 0x0001_0002); + assert_eq!(0x0001_0002.try_into(), Ok(version)); + } +} diff --git a/src/arch/calls.rs b/src/arch/calls.rs new file mode 100644 index 0000000..a06511d --- /dev/null +++ b/src/arch/calls.rs @@ -0,0 +1,43 @@ +// Copyright 2023 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +use super::{ + error::Error, SocIdType, Version, SMCCC_ARCH_FEATURES, SMCCC_ARCH_SOC_ID, + SMCCC_ARCH_WORKAROUND_1, SMCCC_ARCH_WORKAROUND_2, SMCCC_ARCH_WORKAROUND_3, SMCCC_VERSION, +}; +use crate::{ + error::{positive_or_error_32, success_or_error_32}, + Call, +}; + +/// Returns the implemented version of the SMC Calling Convention. +pub fn version<C: Call>() -> Result<Version, Error> { + (C::call32(SMCCC_VERSION, [0; 7])[0] as i32).try_into() +} + +/// Returns whether the given Arm Architecture Service function is implemented, and any feature +/// flags specific to the function. +pub fn features<C: Call>(arch_func_id: u32) -> Result<u32, Error> { + positive_or_error_32(C::call32(SMCCC_ARCH_FEATURES, [arch_func_id, 0, 0, 0, 0, 0, 0])[0]) +} + +/// Returns the SiP defined SoC identification details. +pub fn soc_id<C: Call>(soc_id_type: SocIdType) -> Result<u32, Error> { + positive_or_error_32(C::call32(SMCCC_ARCH_SOC_ID, [soc_id_type.into(), 0, 0, 0, 0, 0, 0])[0]) +} + +/// Executes a firmware workaround to mitigate CVE-2017-5715. +pub fn arch_workaround_1<C: Call>() -> Result<(), Error> { + success_or_error_32(C::call32(SMCCC_ARCH_WORKAROUND_1, [0; 7])[0]) +} + +/// Enables or disables the mitigation for CVE-2018-3639. +pub fn arch_workaround_2<C: Call>(enable: bool) -> Result<(), Error> { + success_or_error_32(C::call32(SMCCC_ARCH_WORKAROUND_2, [enable.into(), 0, 0, 0, 0, 0, 0])[0]) +} + +/// Executes a firmware workaround to mitigate CVE-2017-5715 and CVE-2022-23960. +pub fn arch_workaround_3<C: Call>() -> Result<(), Error> { + success_or_error_32(C::call32(SMCCC_ARCH_WORKAROUND_3, [0; 7])[0]) +} diff --git a/src/arch/error.rs b/src/arch/error.rs new file mode 100644 index 0000000..79bb094 --- /dev/null +++ b/src/arch/error.rs @@ -0,0 +1,58 @@ +// Copyright 2023 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +//! Error codes for standard Arm Architecture SMCCC calls. + +pub use crate::error::SUCCESS; +use core::fmt::{self, Display, Formatter}; + +pub const NOT_SUPPORTED: i32 = -1; +pub const NOT_REQUIRED: i32 = -2; +pub const INVALID_PARAMETER: i32 = -3; + +/// Errors for standard Arm Architecture calls. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Error { + /// The call is not supported by the implementation. + NotSupported, + /// The call is deemed not required by the implementation. + NotRequired, + /// One of the call parameters has a non-supported value. + InvalidParameter, + /// There was an unexpected return value. + Unknown(i32), +} + +impl From<Error> for i32 { + fn from(error: Error) -> i32 { + match error { + Error::NotSupported => NOT_SUPPORTED, + Error::NotRequired => NOT_REQUIRED, + Error::InvalidParameter => INVALID_PARAMETER, + Error::Unknown(value) => value, + } + } +} + +impl From<i32> for Error { + fn from(value: i32) -> Self { + match value { + NOT_SUPPORTED => Error::NotSupported, + NOT_REQUIRED => Error::NotRequired, + INVALID_PARAMETER => Error::InvalidParameter, + _ => Error::Unknown(value), + } + } +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + Self::NotSupported => write!(f, "SMCCC call not supported"), + Self::NotRequired => write!(f, "SMCCC call not required"), + Self::InvalidParameter => write!(f, "SMCCC call received non-supported value"), + Self::Unknown(e) => write!(f, "Unknown SMCCC return value {} ({0:#x})", e), + } + } +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..0267411 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,78 @@ +// Copyright 2023 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +//! Utility functions for error handling. +//! +//! These functions can be combined with the appropriate HVC or SMC functions to wrap calls which +//! return a single value where negative values indicate an error. +//! +//! For example, the [`system_off`](crate::psci::system_off) function is implemented approximately +//! as: +//! +//! ``` +//! # #[cfg(target_arch = "aarch64")] +//! use smccc::{ +//! error::success_or_error_32, +//! psci::{error::Error, PSCI_SYSTEM_OFF}, +//! smc32, +//! }; +//! +//! # #[cfg(target_arch = "aarch64")] +//! pub fn system_off() -> Result<(), Error> { +//! success_or_error_32(smc32(PSCI_SYSTEM_OFF, [0; 7])[0]) +//! } +//! ``` + +/// A value commonly returned to indicate a successful SMCCC call. +pub const SUCCESS: i32 = 0; + +/// Converts the given value (returned from an HVC32 or SMC32 call) either to `Ok(())` if it is +/// equal to [`SUCCESS`], or else an error of the given type. +pub fn success_or_error_32<E: From<i32>>(value: u32) -> Result<(), E> { + let value = value as i32; + if value == SUCCESS { + Ok(()) + } else { + Err(value.into()) + } +} + +/// Converts the given value (returned from an HVC64 or SMC64 call) either to `Ok(())` if it is +/// equal to [`SUCCESS`], or else an error of the given type. +pub fn success_or_error_64<E: From<i64>>(value: u64) -> Result<(), E> { + let value = value as i64; + if value == SUCCESS.into() { + Ok(()) + } else { + Err(value.into()) + } +} + +/// Returns `Ok(value)` if the given value has its high bit unset (i.e. would be positive when +/// treated as a signed value), or an error of the given type if the high bit is set. +/// +/// This is intended to be used with the return value of [`hvc32`](super::hvc32) or +/// [`smc32`](super::smc32). +pub fn positive_or_error_32<E: From<i32>>(value: u32) -> Result<u32, E> { + let signed = value as i32; + if signed < 0 { + Err(signed.into()) + } else { + Ok(value) + } +} + +/// Returns `Ok(value)` if the given value has its high bit unset (i.e. would be positive when +/// treated as a signed value), or an error of the given type if the high bit is set. +/// +/// This is intended to be used with the return value of [`hvc64`](super::hvc64) or +/// [`smc64`](super::smc64). +pub fn positive_or_error_64<E: From<i64>>(value: u64) -> Result<u64, E> { + let signed = value as i64; + if signed < 0 { + Err(signed.into()) + } else { + Ok(value) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..2857ebf --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,172 @@ +// Copyright 2022 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +//! Functions for version 1.4 of the Arm SMC Calling Convention and version 1.1 of the Arm Power +//! State Coordination Interface (PSCI) version 1.1, and relevant constants. +//! +//! Note that the PSCI and SMCCC arch calls may be made via either HVC or SMC. You can choose which +//! one to use by passing either [`Hvc`] or [`Smc`] as a type parameter to the relevant function. +//! +//! This crate currently only supports aarch64 and the SMC64 versions of the PSCI calls, in the +//! cases that both SMC32 and SMC64 versions exist. + +#![no_std] + +pub mod arch; +pub mod error; +pub mod psci; + +/// Use a Hypervisor Call (HVC). +#[cfg(target_arch = "aarch64")] +pub struct Hvc; + +/// Use a Secure Moniter Call (SMC). +#[cfg(target_arch = "aarch64")] +pub struct Smc; + +/// Functions to make an HVC or SMC call. +pub trait Call { + /// Makes a call using the 32-bit calling convention. + fn call32(function: u32, args: [u32; 7]) -> [u32; 8]; + /// Makes a call using the 64-bit calling convention. + fn call64(function: u32, args: [u64; 17]) -> [u64; 18]; +} + +#[cfg(target_arch = "aarch64")] +impl Call for Hvc { + fn call32(function: u32, args: [u32; 7]) -> [u32; 8] { + hvc32(function, args) + } + + fn call64(function: u32, args: [u64; 17]) -> [u64; 18] { + hvc64(function, args) + } +} + +#[cfg(target_arch = "aarch64")] +impl Call for Smc { + fn call32(function: u32, args: [u32; 7]) -> [u32; 8] { + smc32(function, args) + } + + fn call64(function: u32, args: [u64; 17]) -> [u64; 18] { + smc64(function, args) + } +} + +/// Makes an HVC32 call to the hypervisor, following the SMC Calling Convention version 1.3. +#[cfg(target_arch = "aarch64")] +#[inline(always)] +pub fn hvc32(function: u32, args: [u32; 7]) -> [u32; 8] { + unsafe { + let mut ret = [0; 8]; + + core::arch::asm!( + "hvc #0", + inout("w0") function => ret[0], + inout("w1") args[0] => ret[1], + inout("w2") args[1] => ret[2], + inout("w3") args[2] => ret[3], + inout("w4") args[3] => ret[4], + inout("w5") args[4] => ret[5], + inout("w6") args[5] => ret[6], + inout("w7") args[6] => ret[7], + options(nomem, nostack) + ); + + ret + } +} + +/// Makes an SMC32 call to the firmware, following the SMC Calling Convention version 1.3. +#[cfg(target_arch = "aarch64")] +#[inline(always)] +pub fn smc32(function: u32, args: [u32; 7]) -> [u32; 8] { + unsafe { + let mut ret = [0; 8]; + + core::arch::asm!( + "smc #0", + inout("w0") function => ret[0], + inout("w1") args[0] => ret[1], + inout("w2") args[1] => ret[2], + inout("w3") args[2] => ret[3], + inout("w4") args[3] => ret[4], + inout("w5") args[4] => ret[5], + inout("w6") args[5] => ret[6], + inout("w7") args[6] => ret[7], + options(nomem, nostack) + ); + + ret + } +} + +/// Makes an HVC64 call to the hypervisor, following the SMC Calling Convention version 1.3. +#[cfg(target_arch = "aarch64")] +#[inline(always)] +pub fn hvc64(function: u32, args: [u64; 17]) -> [u64; 18] { + unsafe { + let mut ret = [0; 18]; + + core::arch::asm!( + "hvc #0", + inout("x0") function as u64 => ret[0], + inout("x1") args[0] => ret[1], + inout("x2") args[1] => ret[2], + inout("x3") args[2] => ret[3], + inout("x4") args[3] => ret[4], + inout("x5") args[4] => ret[5], + inout("x6") args[5] => ret[6], + inout("x7") args[6] => ret[7], + inout("x8") args[7] => ret[8], + inout("x9") args[8] => ret[9], + inout("x10") args[9] => ret[10], + inout("x11") args[10] => ret[11], + inout("x12") args[11] => ret[12], + inout("x13") args[12] => ret[13], + inout("x14") args[13] => ret[14], + inout("x15") args[14] => ret[15], + inout("x16") args[15] => ret[16], + inout("x17") args[16] => ret[17], + options(nomem, nostack) + ); + + ret + } +} + +/// Makes an SMC64 call to the firmware, following the SMC Calling Convention version 1.3. +#[cfg(target_arch = "aarch64")] +#[inline(always)] +pub fn smc64(function: u32, args: [u64; 17]) -> [u64; 18] { + unsafe { + let mut ret = [0; 18]; + + core::arch::asm!( + "smc #0", + inout("x0") function as u64 => ret[0], + inout("x1") args[0] => ret[1], + inout("x2") args[1] => ret[2], + inout("x3") args[2] => ret[3], + inout("x4") args[3] => ret[4], + inout("x5") args[4] => ret[5], + inout("x6") args[5] => ret[6], + inout("x7") args[6] => ret[7], + inout("x8") args[7] => ret[8], + inout("x9") args[8] => ret[9], + inout("x10") args[9] => ret[10], + inout("x11") args[10] => ret[11], + inout("x12") args[11] => ret[12], + inout("x13") args[12] => ret[13], + inout("x14") args[13] => ret[14], + inout("x15") args[14] => ret[15], + inout("x16") args[15] => ret[16], + inout("x17") args[16] => ret[17], + options(nomem, nostack) + ); + + ret + } +} diff --git a/src/psci.rs b/src/psci.rs new file mode 100644 index 0000000..87dbecd --- /dev/null +++ b/src/psci.rs @@ -0,0 +1,166 @@ +// Copyright 2022 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +//! Constants for version 1.1 of the Arm Power State Coordination Interface (PSCI) version 1.1, and +//! functions to call them. +//! +//! Note that PSCI and other SMCCC calls may be made via either HVC or SMC. You can choose which one +//! to use by building this crate with the corresponding feature (i.e. `hvc` or `smc`). By default +//! `hvc` is enabled. If neither feature is enabled then the functions to make calls will not be +//! available, but the constants and types are still provided. +//! +//! This crate currently only supports aarch64 and the SMC64 versions of the various calls, in the +//! cases that both SMC32 and SMC64 versions exist. + +mod calls; +pub mod error; + +pub use calls::{ + affinity_info, cpu_default_suspend, cpu_freeze, cpu_off, cpu_on, cpu_suspend, mem_protect, + mem_protect_check_range, migrate, migrate_info_type, migrate_info_up_cpu, node_hw_state, + psci_features, set_suspend_mode, stat_count, stat_residency, system_off, system_reset, + system_reset2, system_suspend, version, +}; +pub use error::Error; + +pub const PSCI_VERSION: u32 = 0x84000000; +pub const PSCI_CPU_SUSPEND_32: u32 = 0x84000001; +pub const PSCI_CPU_SUSPEND_64: u32 = 0xC4000001; +pub const PSCI_CPU_OFF: u32 = 0x84000002; +pub const PSCI_CPU_ON_32: u32 = 0x84000003; +pub const PSCI_CPU_ON_64: u32 = 0xC4000003; +pub const PSCI_AFFINITY_INFO_32: u32 = 0x84000004; +pub const PSCI_AFFINITY_INFO_64: u32 = 0xC4000004; +pub const PSCI_MIGRATE_32: u32 = 0x84000005; +pub const PSCI_MIGRATE_64: u32 = 0xC4000005; +pub const PSCI_MIGRATE_INFO_TYPE: u32 = 0x84000006; +pub const PSCI_MIGRATE_INFO_UP_CPU_32: u32 = 0x84000007; +pub const PSCI_MIGRATE_INFO_UP_CPU_64: u32 = 0xC4000007; +pub const PSCI_SYSTEM_OFF: u32 = 0x84000008; +pub const PSCI_SYSTEM_RESET: u32 = 0x84000009; +pub const PSCI_SYSTEM_RESET2_32: u32 = 0x84000012; +pub const PSCI_SYSTEM_RESET2_64: u32 = 0xC4000012; +pub const PSCI_MEM_PROTECT: u32 = 0x84000013; +pub const PSCI_MEM_PROTECT_CHECK_RANGE_32: u32 = 0x84000014; +pub const PSCI_MEM_PROTECT_CHECK_RANGE_64: u32 = 0xC4000014; +pub const PSCI_FEATURES: u32 = 0x8400000A; +pub const PSCI_CPU_FREEZE: u32 = 0x8400000B; +pub const PSCI_CPU_DEFAULT_SUSPEND_32: u32 = 0x8400000C; +pub const PSCI_CPU_DEFAULT_SUSPEND_64: u32 = 0xC400000C; +pub const PSCI_NODE_HW_STATE_32: u32 = 0x8400000D; +pub const PSCI_NODE_HW_STATE_64: u32 = 0xC400000D; +pub const PSCI_SYSTEM_SUSPEND_32: u32 = 0x8400000E; +pub const PSCI_SYSTEM_SUSPEND_64: u32 = 0xC400000E; +pub const PSCI_SET_SUSPEND_MODE: u32 = 0x8400000F; +pub const PSCI_STAT_RESIDENCY_32: u32 = 0x84000010; +pub const PSCI_STAT_RESIDENCY_64: u32 = 0xC4000010; +pub const PSCI_STAT_COUNT_32: u32 = 0x84000011; +pub const PSCI_STAT_COUNT_64: u32 = 0xC4000011; + +/// Selects which affinity level fields are valid in the `target_affinity` parameter to +/// `AFFINITY_INFO`. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum LowestAffinityLevel { + /// All afinity level fields are valid. + All = 0, + /// The `Aff0` field is ignored. + Aff0Ignored = 1, + /// The `Aff0` and `Aff1` fields are ignored. + Aff0Aff1Ignored = 2, + /// The `Aff0`, `Aff1` and `Aff2` fields are ignored. + Aff0Aff1Aff2Ignored = 3, +} + +impl From<LowestAffinityLevel> for u64 { + fn from(lowest_affinity_level: LowestAffinityLevel) -> u64 { + (lowest_affinity_level as u32).into() + } +} + +/// Affinity state values returned by `AFFINITY_INFO`. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum AffinityState { + /// At least one core in the affinity instance is on. + On = 0, + /// All cores in the affinity instance are off. + Off = 1, + /// The affinity instance is transitioning to the on state. + OnPending = 2, +} + +impl TryFrom<i32> for AffinityState { + type Error = Error; + + fn try_from(value: i32) -> Result<Self, Error> { + match value { + 0 => Ok(Self::On), + 1 => Ok(Self::Off), + 2 => Ok(Self::OnPending), + _ => Err(value.into()), + } + } +} + +/// The level of multicore support in the Trusted OS, as returned by `MIGRATE_INFO_TYPE`. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum MigrateType { + /// The Trusted OS will only run on one core, and supports the `MIGRATE` function. + MigrateCapable = 0, + /// The Trusted OS does not support the `MIGRATE` function. + NotMigrateCapable = 1, + /// Either there is no Trusted OS, or it doesn't require migration. + MigrationNotRequired = 2, +} + +impl TryFrom<i32> for MigrateType { + type Error = Error; + + fn try_from(value: i32) -> Result<Self, Error> { + match value { + 0 => Ok(Self::MigrateCapable), + 1 => Ok(Self::NotMigrateCapable), + 2 => Ok(Self::MigrationNotRequired), + _ => Err(value.into()), + } + } +} + +/// The power state of a node in the power domain topology, as returned by `NODE_HW_STATE`. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum PowerState { + /// The node is in the run state. + HwOn = 0, + /// The node is fully powered down. + HwOff = 1, + /// The node is in a standby or retention power state. + HwStandby = 2, +} + +impl TryFrom<i32> for PowerState { + type Error = Error; + + fn try_from(value: i32) -> Result<Self, Error> { + match value { + 0 => Ok(Self::HwOn), + 1 => Ok(Self::HwOff), + 2 => Ok(Self::HwStandby), + _ => Err(value.into()), + } + } +} + +/// The mode to be used by `CPU_SUSPEND`, as set by `PSCI_SET_SUSPEND_MODE`. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum SuspendMode { + /// Platform-coordinated mode. + PlatformCoordinated = 0, + /// OS-initiated mode. + OsInitiated = 1, +} + +impl From<SuspendMode> for u32 { + fn from(suspend_mode: SuspendMode) -> u32 { + suspend_mode as u32 + } +} diff --git a/src/psci/calls.rs b/src/psci/calls.rs new file mode 100644 index 0000000..afc629e --- /dev/null +++ b/src/psci/calls.rs @@ -0,0 +1,354 @@ +// Copyright 2022 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +//! Functions to make PSCI calls. + +use super::{ + error::Error, AffinityState, LowestAffinityLevel, MigrateType, PowerState, SuspendMode, + PSCI_AFFINITY_INFO_64, PSCI_CPU_DEFAULT_SUSPEND_64, PSCI_CPU_FREEZE, PSCI_CPU_OFF, + PSCI_CPU_ON_64, PSCI_CPU_SUSPEND_64, PSCI_FEATURES, PSCI_MEM_PROTECT, + PSCI_MEM_PROTECT_CHECK_RANGE_64, PSCI_MIGRATE_64, PSCI_MIGRATE_INFO_TYPE, + PSCI_MIGRATE_INFO_UP_CPU_64, PSCI_NODE_HW_STATE_64, PSCI_SET_SUSPEND_MODE, PSCI_STAT_COUNT_64, + PSCI_STAT_RESIDENCY_64, PSCI_SYSTEM_OFF, PSCI_SYSTEM_RESET, PSCI_SYSTEM_RESET2_64, + PSCI_SYSTEM_SUSPEND_64, PSCI_VERSION, +}; +use crate::{ + error::{positive_or_error_32, success_or_error_32, success_or_error_64}, + Call, +}; + +/// Returns the version of PSCI implemented. +pub fn version<C: Call>() -> u32 { + C::call32(PSCI_VERSION, [0; 7])[0] +} + +/// Suspends execution of a core or topology node. +pub fn cpu_suspend<C: Call>( + power_state: u32, + entry_point_address: u64, + context_id: u64, +) -> Result<(), Error> { + success_or_error_64( + C::call64( + PSCI_CPU_SUSPEND_64, + [ + power_state.into(), + entry_point_address, + context_id, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0], + ) +} + +/// Powers down the current core. +pub fn cpu_off<C: Call>() -> Result<(), Error> { + success_or_error_32(C::call32(PSCI_CPU_OFF, [0; 7])[0]) +} + +/// Powers up a core. +pub fn cpu_on<C: Call>( + target_cpu: u64, + entry_point_address: u64, + context_id: u64, +) -> Result<(), Error> { + success_or_error_64( + C::call64( + PSCI_CPU_ON_64, + [ + target_cpu, + entry_point_address, + context_id, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0], + ) +} + +/// Gets the status of an affinity instance. +pub fn affinity_info<C: Call>( + target_affinity: u64, + lowest_affinity_level: LowestAffinityLevel, +) -> Result<AffinityState, Error> { + (C::call64( + PSCI_AFFINITY_INFO_64, + [ + target_affinity, + lowest_affinity_level as u64, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0] as i32) + .try_into() +} + +/// Asks the Trusted OS to migrate its context to a specific core. +pub fn migrate<C: Call>(target_cpu: u64) -> Result<(), Error> { + success_or_error_64( + C::call64( + PSCI_MIGRATE_64, + [target_cpu, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + )[0], + ) +} + +/// Identifies the levelof multicore support in the Trusted OS. +pub fn migrate_info_type<C: Call>() -> Result<MigrateType, Error> { + (C::call32(PSCI_MIGRATE_INFO_TYPE, [0; 7])[0] as i32).try_into() +} + +/// Returns the MPIDR value of the current resident core of the Trusted OS. +pub fn migrate_info_up_cpu<C: Call>() -> u64 { + C::call64(PSCI_MIGRATE_INFO_UP_CPU_64, [0; 17])[0] +} + +/// Shuts down the system. +pub fn system_off<C: Call>() -> Result<(), Error> { + success_or_error_32(C::call32(PSCI_SYSTEM_OFF, [0; 7])[0]) +} + +/// Resets the system. +pub fn system_reset<C: Call>() -> Result<(), Error> { + success_or_error_32(C::call32(PSCI_SYSTEM_RESET, [0; 7])[0]) +} + +/// Resets the system in an architectural or vendor-specific way. +pub fn system_reset2<C: Call>(reset_type: u32, cookie: u64) -> Result<(), Error> { + success_or_error_64( + C::call64( + PSCI_SYSTEM_RESET2_64, + [ + reset_type.into(), + cookie, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0], + ) +} + +/// Enables or disables memory protection. +pub fn mem_protect<C: Call>(enable: bool) -> Result<bool, Error> { + match C::call32(PSCI_MEM_PROTECT, [enable as u32, 0, 0, 0, 0, 0, 0])[0] as i32 { + 0 => Ok(false), + 1 => Ok(true), + error => Err(error.into()), + } +} + +/// Checks whether a memory range is protected by `MEM_PROTECT`. +pub fn mem_protect_check_range<C: Call>(base: u64, length: u64) -> Result<(), Error> { + success_or_error_64( + C::call64( + PSCI_MEM_PROTECT_CHECK_RANGE_64, + [base, length, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + )[0], + ) +} + +/// Queries whether `SMCCC_VERSION` or a specific PSCI function is implemented, and what features +/// are supported. +pub fn psci_features<C: Call>(psci_function_id: u32) -> Result<u32, Error> { + positive_or_error_32(C::call32(PSCI_FEATURES, [psci_function_id, 0, 0, 0, 0, 0, 0])[0]) +} + +/// Puts the current core into an implementation-defined low power state. +pub fn cpu_freeze<C: Call>() -> Result<(), Error> { + success_or_error_32(C::call32(PSCI_CPU_FREEZE, [0; 7])[0]) +} + +/// Puts the current core into an implementation-defined low power state. +pub fn cpu_default_suspend<C: Call>( + entry_point_address: u64, + context_id: u64, +) -> Result<(), Error> { + success_or_error_64( + C::call64( + PSCI_CPU_DEFAULT_SUSPEND_64, + [ + entry_point_address, + context_id, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0], + ) +} + +/// Retuns the true hardware state of a node in the power domain topology. +pub fn node_hw_state<C: Call>(target_cpu: u64, power_level: u32) -> Result<PowerState, Error> { + (C::call64( + PSCI_NODE_HW_STATE_64, + [ + target_cpu, + power_level.into(), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0] as i32) + .try_into() +} + +/// Suspends the system to RAM. +pub fn system_suspend<C: Call>(entry_point_address: u64, context_id: u64) -> Result<(), Error> { + success_or_error_64( + C::call64( + PSCI_SYSTEM_SUSPEND_64, + [ + entry_point_address, + context_id, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0], + ) +} + +/// Sets the mode used by `CPU_SUSPEND`. +pub fn set_suspend_mode<C: Call>(mode: SuspendMode) -> Result<(), Error> { + success_or_error_32(C::call32(PSCI_SET_SUSPEND_MODE, [mode.into(), 0, 0, 0, 0, 0, 0])[0]) +} + +/// Returns the amount of time the platform has spend in the given power state since cold boot. +pub fn stat_residency<C: Call>(target_cpu: u64, power_state: u32) -> u64 { + C::call64( + PSCI_STAT_RESIDENCY_64, + [ + target_cpu, + power_state.into(), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0] +} + +/// Returns the number of times the platform has used the given power state since cold boot. +pub fn stat_count<C: Call>(target_cpu: u64, power_state: u32) -> u64 { + C::call64( + PSCI_STAT_COUNT_64, + [ + target_cpu, + power_state.into(), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + )[0] +} diff --git a/src/psci/error.rs b/src/psci/error.rs new file mode 100644 index 0000000..9051eca --- /dev/null +++ b/src/psci/error.rs @@ -0,0 +1,104 @@ +// Copyright 2022 the authors. +// This project is dual-licensed under Apache 2.0 and MIT terms. +// See LICENSE-APACHE and LICENSE-MIT for details. + +//! PSCI error codes. + +pub use crate::error::SUCCESS; +use core::fmt::{self, Display, Formatter}; + +pub const NOT_SUPPORTED: i32 = -1; +pub const INVALID_PARAMETERS: i32 = -2; +pub const DENIED: i32 = -3; +pub const ALREADY_ON: i32 = -4; +pub const ON_PENDING: i32 = -5; +pub const INTERNAL_FAILURE: i32 = -6; +pub const NOT_PRESENT: i32 = -7; +pub const DISABLED: i32 = -8; +pub const INVALID_ADDRESS: i32 = -9; + +/// Standard PSCI errors. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Error { + /// PSCI call not supported. + NotSupported, + /// Invalid parameters to PSCI call. + InvalidParameters, + /// PSCI call denied. + Denied, + /// Core already on. + AlreadyOn, + /// Core already being turned on. + OnPending, + /// Internal failure in PSCI call. + InternalFailure, + /// Trusted OS not present on target core. + NotPresent, + /// Core disabled. + Disabled, + /// Invalid address passed to PSCI call. + InvalidAddress, + /// An unexpected return value from a PSCI function. + Unknown(i64), +} + +impl From<Error> for i64 { + fn from(error: Error) -> i64 { + match error { + Error::NotSupported => NOT_SUPPORTED.into(), + Error::InvalidParameters => INVALID_PARAMETERS.into(), + Error::Denied => DENIED.into(), + Error::AlreadyOn => ALREADY_ON.into(), + Error::OnPending => ON_PENDING.into(), + Error::InternalFailure => INTERNAL_FAILURE.into(), + Error::NotPresent => NOT_PRESENT.into(), + Error::Disabled => DISABLED.into(), + Error::InvalidAddress => INVALID_ADDRESS.into(), + Error::Unknown(value) => value, + } + } +} + +impl From<i32> for Error { + fn from(value: i32) -> Self { + match value { + NOT_SUPPORTED => Error::NotSupported, + INVALID_PARAMETERS => Error::InvalidParameters, + DENIED => Error::Denied, + ALREADY_ON => Error::AlreadyOn, + ON_PENDING => Error::OnPending, + INTERNAL_FAILURE => Error::InternalFailure, + NOT_PRESENT => Error::NotPresent, + DISABLED => Error::Disabled, + INVALID_ADDRESS => Error::InvalidAddress, + _ => Error::Unknown(value.into()), + } + } +} + +impl From<i64> for Error { + fn from(value: i64) -> Self { + if let Ok(value) = i32::try_from(value) { + value.into() + } else { + Error::Unknown(value) + } + } +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + Self::NotSupported => write!(f, "PSCI call not supported"), + Self::InvalidParameters => write!(f, "Invalid parameters to PSCI call"), + Self::Denied => write!(f, "PSCI call denied"), + Self::AlreadyOn => write!(f, "Core already on"), + Self::OnPending => write!(f, "Core already being turned on"), + Self::InternalFailure => write!(f, "Internal failure in PSCI call"), + Self::NotPresent => write!(f, "Trusted OS not present on target core"), + Self::Disabled => write!(f, "Core disabled"), + Self::InvalidAddress => write!(f, "Invalid address passed to PSCI call"), + Self::Unknown(e) => write!(f, "Unknown PSCI return value {} ({0:#x})", e), + } + } +} |