README.md
1# percore
2
3[](https://crates.io/crates/percore)
4[](https://docs.rs/percore)
5
6Safe per-CPU core mutable state on no_std platforms through exception masking.
7
8This crate provides two main wrapper types: `PerCore` to provide an instance of a value per
9CPU core, where each core can access only its instance, and `ExceptionLock` to guard a value
10so that it can only be accessed while exceptions are masked. These may be combined with
11`RefCell` to provide safe per-core mutable state.
12
13`ExceptionLock` may also be combined with a spinlock-based mutex (such as one provided by the
14[`spin`](https://crates.io/crates/spin) crate) to avoid deadlocks when accessing global mutable
15state from exception handlers.
16
17# Example
18
19```rust
20use core::cell::RefCell;
21use percore::{exception_free, Cores, ExceptionLock, PerCore};
22
23/// The total number of CPU cores in the target system.
24const CORE_COUNT: usize = 2;
25
26struct CoresImpl;
27
28unsafe impl Cores for CoresImpl {
29 fn core_index() -> usize {
30 todo!("Return the index of the current CPU core, 0 or 1")
31 }
32}
33
34struct CoreState {
35 // Your per-core mutable state goes here...
36 foo: u32,
37}
38
39const EMPTY_CORE_STATE: ExceptionLock<RefCell<CoreState>> =
40 ExceptionLock::new(RefCell::new(CoreState { foo: 0 }));
41static CORE_STATE: PerCore<ExceptionLock<RefCell<CoreState>>, CoresImpl, CORE_COUNT> =
42 PerCore::new([EMPTY_CORE_STATE; CORE_COUNT]);
43
44fn main() {
45 // Mask exceptions while accessing mutable state.
46 exception_free(|token| {
47 // `token` proves that interrupts are masked, so we can safely access per-core mutable
48 // state.
49 CORE_STATE.get().borrow_mut(token).foo = 42;
50 });
51}
52```
53
54This is not an officially supported Google product.
55
56## Supported architectures
57
58Currently only aarch64 is fully supported. The crate will build for other architectures, but you'll
59need to provide your own implementation of the `exception_free` function. Patches are welcome to add
60support for other architectures.
61
62## License
63
64Licensed under either of
65
66- Apache License, Version 2.0
67 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
68- MIT license
69 ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
70
71at your option.
72
73## Contributing
74
75If you want to contribute to the project, see details of
76[how we accept contributions](CONTRIBUTING.md).
77