Import 'percore' crate

Request Document: go/android-rust-importing-crates
For CL Reviewers: go/android3p#cl-review
For Build Team: go/ab-third-party-imports
Bug: 354713044
Test: m libpercore

Change-Id: Ifb2d820da67717a03bf5d9da4de68102e69e6069
23 files changed
tree: 70366a0807e4349038bf29091a4d05bf1471cd2a
  1. .cargo/
  2. .github/
  3. src/
  4. .cargo_vcs_info.json
  5. .gitignore
  6. Android.bp
  7. AUTHORS
  8. Cargo.toml
  9. Cargo.toml.orig
  10. cargo_embargo.json
  11. CHANGELOG.md
  12. CONTRIBUTING.md
  13. LICENSE
  14. LICENSE-APACHE
  15. LICENSE-MIT
  16. METADATA
  17. MODULE_LICENSE_APACHE2
  18. OWNERS
  19. README.md
README.md

percore

crates.io page docs.rs page

Safe per-CPU core mutable state on no_std platforms through exception masking.

This crate provides two main wrapper types: PerCore to provide an instance of a value per CPU core, where each core can access only its instance, and ExceptionLock to guard a value so that it can only be accessed while exceptions are masked. These may be combined with RefCell to provide safe per-core mutable state.

ExceptionLock may also be combined with a spinlock-based mutex (such as one provided by the spin crate) to avoid deadlocks when accessing global mutable state from exception handlers.

Example

use core::cell::RefCell;
use percore::{exception_free, Cores, ExceptionLock, PerCore};

/// The total number of CPU cores in the target system.
const CORE_COUNT: usize = 2;

struct CoresImpl;

unsafe impl Cores for CoresImpl {
    fn core_index() -> usize {
        todo!("Return the index of the current CPU core, 0 or 1")
    }
}

struct CoreState {
    // Your per-core mutable state goes here...
    foo: u32,
}

const EMPTY_CORE_STATE: ExceptionLock<RefCell<CoreState>> =
    ExceptionLock::new(RefCell::new(CoreState { foo: 0 }));
static CORE_STATE: PerCore<ExceptionLock<RefCell<CoreState>>, CoresImpl, CORE_COUNT> =
    PerCore::new([EMPTY_CORE_STATE; CORE_COUNT]);

fn main() {
    // Mask exceptions while accessing mutable state.
    exception_free(|token| {
        // `token` proves that interrupts are masked, so we can safely access per-core mutable
        // state.
        CORE_STATE.get().borrow_mut(token).foo = 42;
    });
}

This is not an officially supported Google product.

Supported architectures

Currently only aarch64 is fully supported. The crate will build for other architectures, but you'll need to provide your own implementation of the exception_free function. Patches are welcome to add support for other architectures.

License

Licensed under either of

at your option.

Contributing

If you want to contribute to the project, see details of how we accept contributions.