├── .gitignore ├── .github ├── CODEOWNERS ├── bors.toml └── workflows │ ├── rustfmt.yml │ ├── clippy.yml │ └── test.yml ├── LICENSE-MIT ├── Cargo.toml ├── docs └── msrv.md ├── CODE_OF_CONDUCT.md ├── src ├── std.rs ├── mutex.rs └── lib.rs ├── CHANGELOG.md ├── LICENSE-APACHE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @rust-embedded/hal 2 | -------------------------------------------------------------------------------- /.github/bors.toml: -------------------------------------------------------------------------------- 1 | block_labels = ["needs-decision"] 2 | delete_merged_branches = true 3 | required_approvals = 1 4 | status = [ 5 | "clippy (1.54)", 6 | "clippy (1.63)", 7 | "clippy (1.63, std)", 8 | "rustfmt", 9 | "test (1.54)", 10 | "test (1.63)", 11 | "test (1.63, std)", 12 | ] -------------------------------------------------------------------------------- /.github/workflows/rustfmt.yml: -------------------------------------------------------------------------------- 1 | name: Code formatting check 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | merge_group: 8 | 9 | jobs: 10 | rustfmt: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Check fmt 15 | run: cargo fmt -- --check 16 | -------------------------------------------------------------------------------- /.github/workflows/clippy.yml: -------------------------------------------------------------------------------- 1 | name: Clippy check 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | merge_group: 8 | 9 | jobs: 10 | clippy: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | include: 15 | - rust: 1.54 16 | features: '' 17 | - rust: 1.63 18 | features: '' 19 | - rust: 1.63 20 | features: 'std' 21 | - rust: 1.73 22 | features: 'std' 23 | cfgs: "--cfg loom" 24 | 25 | steps: 26 | - uses: actions/checkout@v2 27 | - name: Install Rust 28 | uses: actions-rs/toolchain@v1 29 | with: 30 | toolchain: ${{matrix.rust}} 31 | components: clippy 32 | override: true 33 | - name: Clippy check 34 | run: RUSTFLAGS="${{matrix.cfgs}}" cargo clippy --features "${{matrix.features}}" 35 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | merge_group: 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | include: 15 | - rust: 1.54 16 | features: '' 17 | - rust: 1.63 18 | features: '' 19 | - rust: 1.63 20 | features: 'std' 21 | - rust: 1.73 22 | features: 'std' 23 | cfgs: "--cfg loom" 24 | # Lib tests are the only relevant & working ones 25 | # for loom. 26 | extra_flags: "--lib" 27 | steps: 28 | - uses: actions/checkout@v2 29 | - name: Install Rust 30 | uses: actions-rs/toolchain@v1 31 | with: 32 | toolchain: ${{matrix.rust}} 33 | components: clippy 34 | override: true 35 | - name: Test 36 | run: RUSTFLAGS="${{matrix.cfgs}}" cargo test --features "${{matrix.features}}" ${{matrix.extra_flags}} 37 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2022 The critical-section authors 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "critical-section" 3 | version = "1.2.0" 4 | edition = "2018" 5 | description = "Cross-platform critical section" 6 | repository = "https://github.com/rust-embedded/critical-section" 7 | readme = "README.md" 8 | license = "MIT OR Apache-2.0" 9 | categories = [ 10 | "embedded", 11 | "no-std", 12 | "concurrency", 13 | ] 14 | 15 | [features] 16 | 17 | # Enable a critical-section implementation for platforms supporting `std`, based on `std::sync::Mutex`. 18 | # If you enable this, the `critical-section` crate itself provides the implementation, 19 | # you don't have to get another crate to to do it. 20 | std = ["restore-state-bool"] 21 | 22 | # Set the RestoreState size. 23 | # The crate supplying the critical section implementation can set ONE of them. 24 | # Other crates MUST NOT set any of these. 25 | restore-state-none = [] # Default 26 | restore-state-bool = [] 27 | restore-state-u8 = [] 28 | restore-state-u16 = [] 29 | restore-state-u32 = [] 30 | restore-state-u64 = [] 31 | restore-state-usize = [] 32 | 33 | [target.'cfg(loom)'.dependencies] 34 | loom = "0.7.2" 35 | 36 | [lints.rust] 37 | unexpected_cfgs = { level = "allow", check-cfg = ['cfg(loom)'] } 38 | -------------------------------------------------------------------------------- /docs/msrv.md: -------------------------------------------------------------------------------- 1 | # Minimum Supported Rust Version (MSRV) 2 | 3 | This crate is guaranteed to compile on all stable Rust versions going back to 4 | the version stated as MSRV in the README. It *might* compile with even older versions but 5 | that may change in any new patch release. 6 | 7 | ## How the MSRV will be upgraded 8 | 9 | For `critical-section`, we do not consider upgrading the MSRV a strictly breaking change as defined by 10 | [SemVer](https://semver.org). 11 | 12 | We follow these rules when upgrading it: 13 | 14 | - We will not update the MSRV on any patch release: \_.\_.*Z*. 15 | - We may upgrade the MSRV on any *major* or *minor* release: *X*.*Y*.\_. 16 | - We may upgrade the MSRV in any preliminary version release (e.g. an `-alpha` release) as 17 | these serve as preparation for the final release. 18 | - MSRV upgrades will be clearly stated in the changelog. 19 | 20 | This applies both to `0._._` releases as well as `>=1._._` releases. 21 | 22 | For example: 23 | 24 | For a given `x.y.z` release, we may upgrade the MSRV on `x` and `y` releases but not on `z` releases. 25 | 26 | If your MSRV upgrade policy differs from this, you are advised to specify the 27 | `critical-section` dependency in your `Cargo.toml` accordingly. 28 | 29 | See the [Rust Embedded Working Group MSRV RFC](https://github.com/rust-embedded/wg/blob/master/rfcs/0523-msrv-2020.md) 30 | for more background information and reasoning. 31 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # The Rust Code of Conduct 2 | 3 | ## Conduct 4 | 5 | **Contact**: [HAL team][team] 6 | 7 | * We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic. 8 | * On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all. 9 | * Please be kind and courteous. There's no need to be mean or rude. 10 | * Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer. 11 | * Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works. 12 | * We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups. 13 | * Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [HAL team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back. 14 | * Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome. 15 | 16 | ## Moderation 17 | 18 | These are the policies for upholding our community's standards of conduct. 19 | 20 | 1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.) 21 | 2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed. 22 | 3. Moderators will first respond to such remarks with a warning. 23 | 4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off. 24 | 5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded. 25 | 6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology. 26 | 7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed. 27 | 8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others. 28 | 29 | In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely. 30 | 31 | And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust. 32 | 33 | The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org). 34 | 35 | *Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).* 36 | 37 | [team]: https://github.com/rust-embedded/wg#the-hal-team 38 | -------------------------------------------------------------------------------- /src/std.rs: -------------------------------------------------------------------------------- 1 | use std::mem::MaybeUninit; 2 | 3 | #[cfg(not(loom))] 4 | use std::{ 5 | cell::Cell, 6 | sync::{Mutex, MutexGuard}, 7 | thread_local, 8 | }; 9 | 10 | #[cfg(loom)] 11 | use loom::{ 12 | cell::Cell, 13 | sync::{Mutex, MutexGuard}, 14 | thread_local, 15 | }; 16 | 17 | #[cfg(not(loom))] 18 | static GLOBAL_MUTEX: Mutex<()> = Mutex::new(()); 19 | 20 | #[cfg(loom)] 21 | loom::lazy_static! { 22 | static ref GLOBAL_MUTEX: Mutex<()> = Mutex::new(()); 23 | } 24 | 25 | // This is initialized if a thread has acquired the CS, uninitialized otherwise. 26 | static mut GLOBAL_GUARD: MaybeUninit> = MaybeUninit::uninit(); 27 | 28 | thread_local!(static IS_LOCKED: Cell = Cell::new(false)); 29 | 30 | struct StdCriticalSection; 31 | crate::set_impl!(StdCriticalSection); 32 | 33 | unsafe impl crate::Impl for StdCriticalSection { 34 | unsafe fn acquire() -> bool { 35 | // Allow reentrancy by checking thread local state 36 | IS_LOCKED.with(|l| { 37 | if l.get() { 38 | // CS already acquired in the current thread. 39 | return true; 40 | } 41 | 42 | // Note: it is fine to set this flag *before* acquiring the mutex because it's thread local. 43 | // No other thread can see its value, there's no potential for races. 44 | // This way, we hold the mutex for slightly less time. 45 | l.set(true); 46 | 47 | // Not acquired in the current thread, acquire it. 48 | let guard = match GLOBAL_MUTEX.lock() { 49 | Ok(guard) => guard, 50 | Err(err) => { 51 | // Ignore poison on the global mutex in case a panic occurred 52 | // while the mutex was held. 53 | err.into_inner() 54 | } 55 | }; 56 | GLOBAL_GUARD.write(guard); 57 | 58 | false 59 | }) 60 | } 61 | 62 | unsafe fn release(nested_cs: bool) { 63 | if !nested_cs { 64 | // SAFETY: As per the acquire/release safety contract, release can only be called 65 | // if the critical section is acquired in the current thread, 66 | // in which case we know the GLOBAL_GUARD is initialized. 67 | // 68 | // We have to `assume_init_read` then drop instead of `assume_init_drop` because: 69 | // - drop requires exclusive access (&mut) to the contents 70 | // - mutex guard drop first unlocks the mutex, then returns. In between those, there's a brief 71 | // moment where the mutex is unlocked but a `&mut` to the contents exists. 72 | // - During this moment, another thread can go and use GLOBAL_GUARD, causing `&mut` aliasing. 73 | #[allow(let_underscore_lock)] 74 | let _ = GLOBAL_GUARD.assume_init_read(); 75 | 76 | // Note: it is fine to clear this flag *after* releasing the mutex because it's thread local. 77 | // No other thread can see its value, there's no potential for races. 78 | // This way, we hold the mutex for slightly less time. 79 | IS_LOCKED.with(|l| l.set(false)); 80 | } 81 | } 82 | } 83 | 84 | #[cfg(test)] 85 | #[cfg(not(loom))] 86 | mod tests { 87 | use std::thread; 88 | 89 | use crate as critical_section; 90 | 91 | #[cfg(feature = "std")] 92 | #[test] 93 | #[should_panic(expected = "Not a PoisonError!")] 94 | fn reusable_after_panic() { 95 | let _ = thread::spawn(|| { 96 | critical_section::with(|_| { 97 | panic!("Boom!"); 98 | }) 99 | }) 100 | .join(); 101 | 102 | critical_section::with(|_| { 103 | panic!("Not a PoisonError!"); 104 | }) 105 | } 106 | } 107 | 108 | #[cfg(test)] 109 | #[cfg(loom)] 110 | mod tests { 111 | use crate as critical_section; 112 | 113 | #[cfg(feature = "std")] 114 | #[test] 115 | #[should_panic(expected = "Not a PoisonError!")] 116 | fn reusable_after_panic_loom() { 117 | loom::model(|| { 118 | // IMPORTANT: using `std::thread` here because `loom` is effectively 119 | // single-threaded, so panicking in `loom::thread` will panic the 120 | // entire test. 121 | let _ = std::thread::spawn(|| { 122 | critical_section::with(|_| { 123 | panic!("Boom!"); 124 | }); 125 | }) 126 | .join(); 127 | 128 | critical_section::with(|_| { 129 | panic!("Not a PoisonError!"); 130 | }) 131 | }) 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | No unreleased changes yet 11 | 12 | ## [v1.2.0] - 2024-10-16 13 | 14 | - Soundness fix: ensure the `CriticalSection` token is not `Send` or `Sync`, so that it can only be used in the thread that acquired it. [#55](https://github.com/rust-embedded/critical-section/issues/55) 15 | - Soundness fix: Fix aliasing `&mut` in the `std` implementation. [#46](https://github.com/rust-embedded/critical-section/pull/46) 16 | - Fix build with `restore-state-usize`. [#50](https://github.com/rust-embedded/critical-section/pull/50) 17 | 18 | ## [v1.1.3] - 2024-08-22 19 | 20 | - Added option to use a `usize` sized restore state 21 | 22 | ## [v1.1.2] - 2023-08-09 23 | 24 | - Clarified that `acquire()` must provide ordering guarantees 25 | - Updated atomic-polyfill reference to point to portable-atomic instead 26 | - Improved documentation for `Mutex` example 27 | - Added list of some known implementations 28 | 29 | ## [v1.1.1] - 2022-09-13 30 | 31 | - On the `std` implementation, panicking inside the `critical_section::with()` closure no longer accidentally leaves the critical section locked (#26). 32 | 33 | ## [v1.1.0] - 2022-08-17 34 | 35 | - Added built-in critical section implementation using `std::sync::Mutex`, enabled by the `std` Cargo feature. 36 | - MSRV changed to `1.54` when `std` feature is disabled, `1.63` when enabled. 37 | 38 | ## [v1.0.0] - 2022-08-10 39 | 40 | - Improved docs. 41 | 42 | ## [v1.0.0-alpha.2] - 2022-07-28 43 | 44 | - Change name of the `extern fn`s to avoid clash with critical-section 0.2. 45 | 46 | ## [v1.0.0-alpha.1] - 2022-07-28 47 | 48 | Breaking changes: 49 | 50 | - Removed all builtin impls. These are going to be provided by platform-support crates now. 51 | - Renamed `custom_impl!` to `set_impl!`. 52 | - RestoreState is now an opaque struct for the user, and a transparent `RawRestoreState` type alias for impl writers. 53 | - RestoreState type is now configurable with Cargo features. Default is `()`. (previously it was fixed to `u8`.) 54 | - Added own `CriticalSection` and `Mutex` types, instead of reexporting them from `bare_metal`. 55 | 56 | ## [v0.2.8] - 2022-11-29 57 | 58 | - Implemented critical-section by forwarding to version 1.1.1 59 | 60 | Breaking changes: 61 | 62 | - `acquire` and `release` are only implemented if the restore-state used by 63 | version 1.1.1 is an u8 or smaller. 64 | - No default critical-section implementation is provided. 65 | 66 | Those breaking changes are necessary because versions <= 0.2.7 were unsound, and that 67 | was impossible to fix without a breaking change. 68 | 69 | This version is meant to minimize that breaking change. However, all 70 | users are encouraged to upgrade to critical-section 1.1. 71 | 72 | If you're seeing a linker error like `undefined symbol: _critical_section_1_0_acquire`, you're affected. To fix it: 73 | 74 | - If your target supports `std`: Add the `critical-section` dependency to `Cargo.toml` enabling the `std` feature. 75 | 76 | ```toml 77 | [dependencies] 78 | critical-section = { version = "1.1", features = ["std"]} 79 | ``` 80 | 81 | - For single-core Cortex-M targets in privileged mode: 82 | ```toml 83 | [dependencies] 84 | cortex-m = { version = "0.7.6", features = ["critical-section-single-core"]} 85 | ``` 86 | 87 | - For single-hart RISC-V targets in privileged mode: 88 | ```toml 89 | [dependencies] 90 | riscv = { version = "0.10", features = ["critical-section-single-hart"]} 91 | ``` 92 | 93 | - For other targets: check if your HAL or architecture-support crate has a `critical-section 1.0` implementation available. Otherwise, [provide your own](https://github.com/rust-embedded/critical-section#providing-an-implementation). 94 | 95 | 96 | ## [v0.2.7] - 2022-04-08 97 | 98 | - Add support for AVR targets. 99 | 100 | ## [v0.2.6] - 2022-04-02 101 | 102 | - Improved docs. 103 | 104 | ## [v0.2.5] - 2021-11-02 105 | 106 | - Fix `std` implementation to allow reentrant (nested) critical sections. This would previously deadlock. 107 | 108 | ## [v0.2.4] - 2021-09-24 109 | 110 | - Add support for 32bit RISC-V targets. 111 | 112 | ## [v0.2.3] - 2021-09-13 113 | 114 | - Use correct `#[vcfg]` for `wasm` targets. 115 | 116 | ## [v0.2.2] - 2021-09-13 117 | 118 | - Added support for `wasm` targets. 119 | 120 | ## [v0.2.1] - 2021-05-11 121 | 122 | - Added critical section implementation for `std`, based on a global Mutex. 123 | 124 | ## [v0.2.0] - 2021-05-10 125 | 126 | - Breaking change: use `CriticalSection<'_>` instead of `&CriticalSection<'_>` 127 | 128 | ## v0.1.0 - 2021-05-10 129 | 130 | - First release 131 | 132 | [Unreleased]: https://github.com/rust-embedded/critical-section/compare/v1.2.0...HEAD 133 | [v1.2.0]: https://github.com/rust-embedded/critical-section/compare/v1.1.3...v1.2.0 134 | [v1.1.3]: https://github.com/rust-embedded/critical-section/compare/v1.1.2...v1.1.3 135 | [v1.1.2]: https://github.com/rust-embedded/critical-section/compare/v1.1.1...v1.1.2 136 | [v1.1.1]: https://github.com/rust-embedded/critical-section/compare/v1.1.0...v1.1.1 137 | [v1.1.0]: https://github.com/rust-embedded/critical-section/compare/v1.0.0...v1.1.0 138 | [v1.0.0]: https://github.com/rust-embedded/critical-section/compare/v1.0.0-alpha.2...v1.0.0 139 | [v1.0.0-alpha.2]: https://github.com/rust-embedded/critical-section/compare/v1.0.0-alpha.1...v1.0.0-alpha.2 140 | [v1.0.0-alpha.1]: https://github.com/rust-embedded/critical-section/compare/v0.2.7...v1.0.0-alpha.1 141 | [v0.2.8]: https://github.com/rust-embedded/critical-section/compare/v0.2.7...v0.2.8 142 | [v0.2.7]: https://github.com/rust-embedded/critical-section/compare/v0.2.6...v0.2.7 143 | [v0.2.6]: https://github.com/rust-embedded/critical-section/compare/v0.2.5...v0.2.6 144 | [v0.2.5]: https://github.com/rust-embedded/critical-section/compare/v0.2.4...v0.2.5 145 | [v0.2.4]: https://github.com/rust-embedded/critical-section/compare/v0.2.3...v0.2.4 146 | [v0.2.3]: https://github.com/rust-embedded/critical-section/compare/v0.2.2...v0.2.3 147 | [v0.2.2]: https://github.com/rust-embedded/critical-section/compare/v0.2.1...v0.2.2 148 | [v0.2.1]: https://github.com/rust-embedded/critical-section/compare/v0.2.0...v0.2.1 149 | [v0.2.0]: https://github.com/rust-embedded/critical-section/compare/v0.1.0...v0.2.0 150 | -------------------------------------------------------------------------------- /src/mutex.rs: -------------------------------------------------------------------------------- 1 | use super::CriticalSection; 2 | use core::cell::{Ref, RefCell, RefMut, UnsafeCell}; 3 | 4 | /// A mutex based on critical sections. 5 | /// 6 | /// # Example 7 | /// 8 | /// ```no_run 9 | /// # use critical_section::Mutex; 10 | /// # use std::cell::Cell; 11 | /// 12 | /// static FOO: Mutex> = Mutex::new(Cell::new(42)); 13 | /// 14 | /// fn main() { 15 | /// critical_section::with(|cs| { 16 | /// FOO.borrow(cs).set(43); 17 | /// }); 18 | /// } 19 | /// 20 | /// fn interrupt_handler() { 21 | /// let _x = critical_section::with(|cs| FOO.borrow(cs).get()); 22 | /// } 23 | /// ``` 24 | /// 25 | /// 26 | /// # Design 27 | /// 28 | /// [`std::sync::Mutex`] has two purposes. It converts types that are [`Send`] 29 | /// but not [`Sync`] into types that are both; and it provides 30 | /// [interior mutability]. `critical_section::Mutex`, on the other hand, only adds 31 | /// `Sync`. It does *not* provide interior mutability. 32 | /// 33 | /// This was a conscious design choice. It is possible to create multiple 34 | /// [`CriticalSection`] tokens, either by nesting critical sections or `Copy`ing 35 | /// an existing token. As a result, it would not be sound for [`Mutex::borrow`] 36 | /// to return `&mut T`, because there would be nothing to prevent calling 37 | /// `borrow` multiple times to create aliased `&mut T` references. 38 | /// 39 | /// The solution is to include a runtime check to ensure that each resource is 40 | /// borrowed only once. This is what `std::sync::Mutex` does. However, this is 41 | /// a runtime cost that may not be required in all circumstances. For instance, 42 | /// `Mutex>` never needs to create `&mut T` or equivalent. 43 | /// 44 | /// If `&mut T` is needed, the simplest solution is to use `Mutex>`, 45 | /// which is the closest analogy to `std::sync::Mutex`. [`RefCell`] inserts the 46 | /// exact runtime check necessary to guarantee that the `&mut T` reference is 47 | /// unique. 48 | /// 49 | /// To reduce verbosity when using `Mutex>`, we reimplement some of 50 | /// `RefCell`'s methods on it directly. 51 | /// 52 | /// ```no_run 53 | /// # use critical_section::Mutex; 54 | /// # use std::cell::RefCell; 55 | /// 56 | /// static FOO: Mutex> = Mutex::new(RefCell::new(42)); 57 | /// 58 | /// fn main() { 59 | /// critical_section::with(|cs| { 60 | /// // Instead of calling this 61 | /// let _ = FOO.borrow(cs).take(); 62 | /// // Call this 63 | /// let _ = FOO.take(cs); 64 | /// // `RefCell::borrow` and `RefCell::borrow_mut` are renamed to 65 | /// // `borrow_ref` and `borrow_ref_mut` to avoid name collisions 66 | /// let _: &mut i32 = &mut *FOO.borrow_ref_mut(cs); 67 | /// }) 68 | /// } 69 | /// ``` 70 | /// 71 | /// [`std::sync::Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html 72 | /// [interior mutability]: https://doc.rust-lang.org/reference/interior-mutability.html 73 | #[derive(Debug)] 74 | pub struct Mutex { 75 | // The `UnsafeCell` is not strictly necessary here: In theory, just using `T` should 76 | // be fine. 77 | // However, without `UnsafeCell`, the compiler may use niches inside `T`, and may 78 | // read the niche value _without locking the mutex_. As we don't provide interior 79 | // mutability, this is still not violating any aliasing rules and should be perfectly 80 | // fine. But as the cost of adding `UnsafeCell` is very small, we add it out of 81 | // cautiousness, just in case the reason `T` is not `Sync` in the first place is 82 | // something very obscure we didn't consider. 83 | inner: UnsafeCell, 84 | } 85 | 86 | impl Mutex { 87 | /// Creates a new mutex. 88 | #[inline] 89 | pub const fn new(value: T) -> Self { 90 | Mutex { 91 | inner: UnsafeCell::new(value), 92 | } 93 | } 94 | 95 | /// Gets a mutable reference to the contained value when the mutex is already uniquely borrowed. 96 | /// 97 | /// This does not require locking or a critical section since it takes `&mut self`, which 98 | /// guarantees unique ownership already. Care must be taken when using this method to 99 | /// **unsafely** access `static mut` variables, appropriate fences must be used to prevent 100 | /// unwanted optimizations. 101 | #[inline] 102 | pub fn get_mut(&mut self) -> &mut T { 103 | unsafe { &mut *self.inner.get() } 104 | } 105 | 106 | /// Unwraps the contained value, consuming the mutex. 107 | #[inline] 108 | pub fn into_inner(self) -> T { 109 | self.inner.into_inner() 110 | } 111 | 112 | /// Borrows the data for the duration of the critical section. 113 | #[inline] 114 | pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T { 115 | unsafe { &*self.inner.get() } 116 | } 117 | } 118 | 119 | impl Mutex> { 120 | /// Borrow the data and call [`RefCell::replace`] 121 | /// 122 | /// This is equivalent to `self.borrow(cs).replace(t)` 123 | /// 124 | /// # Panics 125 | /// 126 | /// This call could panic. See the documentation for [`RefCell::replace`] 127 | /// for more details. 128 | #[inline] 129 | #[track_caller] 130 | pub fn replace<'cs>(&'cs self, cs: CriticalSection<'cs>, t: T) -> T { 131 | self.borrow(cs).replace(t) 132 | } 133 | 134 | /// Borrow the data and call [`RefCell::replace_with`] 135 | /// 136 | /// This is equivalent to `self.borrow(cs).replace_with(f)` 137 | /// 138 | /// # Panics 139 | /// 140 | /// This call could panic. See the documentation for 141 | /// [`RefCell::replace_with`] for more details. 142 | #[inline] 143 | #[track_caller] 144 | pub fn replace_with<'cs, F>(&'cs self, cs: CriticalSection<'cs>, f: F) -> T 145 | where 146 | F: FnOnce(&mut T) -> T, 147 | { 148 | self.borrow(cs).replace_with(f) 149 | } 150 | 151 | /// Borrow the data and call [`RefCell::borrow`] 152 | /// 153 | /// This is equivalent to `self.borrow(cs).borrow()` 154 | /// 155 | /// # Panics 156 | /// 157 | /// This call could panic. See the documentation for [`RefCell::borrow`] 158 | /// for more details. 159 | #[inline] 160 | #[track_caller] 161 | pub fn borrow_ref<'cs>(&'cs self, cs: CriticalSection<'cs>) -> Ref<'cs, T> { 162 | self.borrow(cs).borrow() 163 | } 164 | 165 | /// Borrow the data and call [`RefCell::borrow_mut`] 166 | /// 167 | /// This is equivalent to `self.borrow(cs).borrow_mut()` 168 | /// 169 | /// # Panics 170 | /// 171 | /// This call could panic. See the documentation for [`RefCell::borrow_mut`] 172 | /// for more details. 173 | #[inline] 174 | #[track_caller] 175 | pub fn borrow_ref_mut<'cs>(&'cs self, cs: CriticalSection<'cs>) -> RefMut<'cs, T> { 176 | self.borrow(cs).borrow_mut() 177 | } 178 | } 179 | 180 | impl Mutex> { 181 | /// Borrow the data and call [`RefCell::take`] 182 | /// 183 | /// This is equivalent to `self.borrow(cs).take()` 184 | /// 185 | /// # Panics 186 | /// 187 | /// This call could panic. See the documentation for [`RefCell::take`] 188 | /// for more details. 189 | #[inline] 190 | #[track_caller] 191 | pub fn take<'cs>(&'cs self, cs: CriticalSection<'cs>) -> T { 192 | self.borrow(cs).take() 193 | } 194 | } 195 | 196 | // NOTE A `Mutex` can be used as a channel so the protected data must be `Send` 197 | // to prevent sending non-Sendable stuff (e.g. access tokens) across different 198 | // threads. 199 | unsafe impl Sync for Mutex where T: Send {} 200 | 201 | /// ``` compile_fail 202 | /// fn bad(cs: critical_section::CriticalSection) -> &u32 { 203 | /// let x = critical_section::Mutex::new(42u32); 204 | /// x.borrow(cs) 205 | /// } 206 | /// ``` 207 | #[cfg(doctest)] 208 | const BorrowMustNotOutliveMutexTest: () = (); 209 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # critical-section 2 | [![crates.io](https://img.shields.io/crates/d/critical-section.svg)](https://crates.io/crates/critical-section) 3 | [![crates.io](https://img.shields.io/crates/v/critical-section.svg)](https://crates.io/crates/critical-section) 4 | [![Documentation](https://docs.rs/critical-section/badge.svg)](https://docs.rs/critical-section) 5 | 6 | This project is developed and maintained by the [HAL team][team]. 7 | 8 | A critical section that works everywhere! 9 | 10 | When writing software for embedded systems, it's common to use a "critical section" 11 | as a basic primitive to control concurrency. A critical section is essentially a 12 | mutex global to the whole process, that can be acquired by only one thread at a time. 13 | This can be used to protect data behind mutexes, to [emulate atomics](https://crates.io/crates/portable-atomic) in 14 | targets that don't support them, etc. 15 | 16 | There's a wide range of possible implementations depending on the execution environment: 17 | - For bare-metal single core, disabling interrupts in the current (only) core. 18 | - For bare-metal multicore, disabling interrupts in the current core and acquiring a hardware spinlock to prevent other cores from entering a critical section concurrently. 19 | - For bare-metal using a RTOS, using library functions for acquiring a critical section, often named "scheduler lock" or "kernel lock". 20 | - For bare-metal running in non-privileged mode, calling some system call is usually needed. 21 | - For `std` targets, acquiring a global `std::sync::Mutex`. 22 | 23 | Libraries often need to use critical sections, but there's no universal API for this in `core`. This leads 24 | library authors to hard-code them for their target, or at best add some `cfg`s to support a few targets. 25 | This doesn't scale since there are many targets out there, and in the general case it's impossible to know 26 | which critical section implementation is needed from the Rust target alone. For example, the `thumbv7em-none-eabi` target 27 | could be cases 1-4 from the above list. 28 | 29 | This crate solves the problem by providing this missing universal API. 30 | 31 | - It provides functions `acquire`, `release` and `with` that libraries can directly use. 32 | - It provides a way for any crate to supply an implementation. This allows "target support" crates such as architecture crates (`cortex-m`, `riscv`), RTOS bindings, or HALs for multicore chips to supply the correct implementation so that all the crates in the dependency tree automatically use it. 33 | 34 | ## Usage in `no-std` binaries. 35 | 36 | First, add a dependency on a crate providing a critical section implementation. Enable the `critical-section-*` Cargo feature if required by the crate. 37 | 38 | Implementations are typically provided by either architecture-support crates, HAL crates, and OS/RTOS bindings, including: 39 | 40 | * The [`cortex-m`] crate provides an implementation for all single-core Cortex-M microcontrollers via its `critical-section-single-core` feature 41 | * The [`riscv`] crate provides an implementation for all single-hart RISC-V microcontrollers via its `critical-section-single-hart` feature 42 | * The [`msp430`] crate provides an implementation for all MSP430 microcontrollers via its `critical-section-single-core` feature 43 | * The [`rp2040-hal`] crate provides a multi-core-safe critical section for the RP2040 microcontroller via its `critical-section-impl` feature 44 | * The [`avr-device`] crate provides an implementation for all AVR microcontrollers via its `critical-section-impl` feature 45 | * The [`esp-hal`] crate provides an implementation for ESP32 microcontrollers which is used by the ESP HALs 46 | * The [`embassy-rp`] crate provides a multi-core-safe critical section for the RP2040 microcontroller via its `critical-section-impl` feature 47 | * The [`nrf-softdevice`] crate provides a critical section that's compatible with the nRF soft-device firmware via its `critical-section-impl` feature 48 | 49 | [`cortex-m`]: https://crates.io/crates/cortex-m 50 | [`riscv`]: https://crates.io/crates/riscv 51 | [`msp430`]: https://crates.io/crates/msp430 52 | [`rp2040-hal`]: https://crates.io/crates/rp2040-hal 53 | [`avr-device`]: https://crates.io/crates/avr-device 54 | [`esp-hal`]: https://crates.io/crates/esp-hal 55 | [`embassy-rp`]: https://docs.embassy.dev/embassy-rp 56 | [`nrf-softdevice`]: https://docs.embassy.dev/nrf-softdevice 57 | 58 | For example, for single-core Cortex-M targets, you can use: 59 | 60 | ```toml 61 | [dependencies] 62 | cortex-m = { version = "0.7.6", features = ["critical-section-single-core"]} 63 | ``` 64 | 65 | Then you can use `critical_section::with()`. 66 | 67 | ```rust 68 | use core::cell::Cell; 69 | use critical_section::Mutex; 70 | 71 | static MY_VALUE: Mutex> = Mutex::new(Cell::new(0)); 72 | 73 | critical_section::with(|cs| { 74 | // This code runs within a critical section. 75 | 76 | // `cs` is a token that you can use to "prove" that to some API, 77 | // for example to a `Mutex`: 78 | MY_VALUE.borrow(cs).set(42); 79 | }); 80 | 81 | # #[cfg(not(feature = "std"))] // needed for `cargo test --features std` 82 | # mod no_std { 83 | # struct MyCriticalSection; 84 | # critical_section::set_impl!(MyCriticalSection); 85 | # unsafe impl critical_section::Impl for MyCriticalSection { 86 | # unsafe fn acquire() -> () {} 87 | # unsafe fn release(token: ()) {} 88 | # } 89 | # } 90 | ``` 91 | 92 | ## Usage in `std` binaries. 93 | 94 | Add the `critical-section` dependency to `Cargo.toml` enabling the `std` feature. This makes the `critical-section` crate itself 95 | provide an implementation based on `std::sync::Mutex`, so you don't have to add any other dependency. 96 | 97 | ```toml 98 | [dependencies] 99 | critical-section = { version = "1.1", features = ["std"]} 100 | ``` 101 | 102 | ## Usage in [`loom`] tests 103 | 104 | `critical-section` supports [`loom`] by enabling the `std` feature and passing `--cfg loom` as `RUSTFLAGS` (either through `.cargo/config.toml`, or through the environment variable). 105 | This implementation is identical to the normal `std` implementation, but uses `loom` synchronization primitives instead. 106 | 107 | [`loom`]: https://docs.rs/loom/latest/loom/#writing-tests 108 | 109 | ## Usage in libraries 110 | 111 | If you're writing a library intended to be portable across many targets, simply add a dependency on `critical-section` 112 | and use `critical_section::free` and/or `Mutex` as usual. 113 | 114 | **Do not** add any dependency supplying a critical section implementation. Do not enable any `critical-section-*` Cargo feature. 115 | This has to be done by the end user, enabling the correct implementation for their target. 116 | 117 | **Do not** enable any Cargo feature in `critical-section`. 118 | 119 | ## Usage in `std` tests for `no-std` libraries. 120 | 121 | If you want to run `std`-using tests in otherwise `no-std` libraries, enable the `std` feature in `dev-dependencies` only. 122 | This way the main target will use the `no-std` implementation chosen by the end-user's binary, and only the test targets 123 | will use the `std` implementation. 124 | 125 | ```toml 126 | [dependencies] 127 | critical-section = "1.1" 128 | 129 | [dev-dependencies] 130 | critical-section = { version = "1.1", features = ["std"]} 131 | ``` 132 | 133 | ## Providing an implementation 134 | 135 | Crates adding support for a particular architecture, chip or operating system should provide a critical section implementation. 136 | It is **strongly recommended** to gate the implementation behind a feature, so the user can still use another implementation 137 | if needed (having two implementations in the same binary will cause linking to fail). 138 | 139 | Add the dependency, and a `critical-section-*` feature to your `Cargo.toml`: 140 | 141 | ```toml 142 | [features] 143 | # Enable critical section implementation that does "foo" 144 | critical-section-foo = ["critical-section/restore-state-bool"] 145 | 146 | [dependencies] 147 | critical-section = { version = "1.0", optional = true } 148 | ``` 149 | 150 | Then, provide the critical implementation like this: 151 | 152 | ```rust 153 | # #[cfg(not(feature = "std"))] // needed for `cargo test --features std` 154 | # mod no_std { 155 | // This is a type alias for the enabled `restore-state-*` feature. 156 | // For example, it is `bool` if you enable `restore-state-bool`. 157 | use critical_section::RawRestoreState; 158 | 159 | struct MyCriticalSection; 160 | critical_section::set_impl!(MyCriticalSection); 161 | 162 | unsafe impl critical_section::Impl for MyCriticalSection { 163 | unsafe fn acquire() -> RawRestoreState { 164 | // TODO 165 | } 166 | 167 | unsafe fn release(token: RawRestoreState) { 168 | // TODO 169 | } 170 | } 171 | # } 172 | ``` 173 | 174 | ## Troubleshooting 175 | 176 | ### Undefined reference errors 177 | 178 | If you get an error like these: 179 | 180 | ```not_rust 181 | undefined reference to `_critical_section_1_0_acquire' 182 | undefined reference to `_critical_section_1_0_release' 183 | ``` 184 | 185 | it is because you (or a library) are using `critical_section::with` without providing a critical section implementation. 186 | Make sure you're depending on a crate providing the implementation, and have enabled the `critical-section-*` feature in it if required. See the `Usage` section above. 187 | 188 | The error can also be caused by having the dependency but never `use`ing it. This can be fixed by adding a dummy `use`: 189 | 190 | ```rust,ignore 191 | use the_cs_impl_crate as _; 192 | ``` 193 | 194 | ### Duplicate symbol errors 195 | 196 | If you get errors like these: 197 | 198 | ```not_rust 199 | error: symbol `_critical_section_1_0_acquire` is already defined 200 | ``` 201 | 202 | it is because you have two crates trying to provide a critical section implementation. You can only 203 | have one implementation in a program. 204 | 205 | You can use `cargo tree --format '{p} {f}'` to view all dependencies and their enabled features. Make sure 206 | that in the whole dependency tree, exactly one implementation is provided. 207 | 208 | Check for multiple versions of the same crate as well. For example, check the `critical-section-single-core` 209 | feature is not enabled for both `cortex-m` 0.7 and 0.8. 210 | 211 | ## Why not generics? 212 | 213 | An alternative solution would be to use a `CriticalSection` trait, and make all 214 | code that needs acquiring the critical section generic over it. This has a few problems: 215 | 216 | - It would require passing it as a generic param to a very big amount of code, which 217 | would be quite unergonomic. 218 | - It's common to put `Mutex`es in `static` variables, and `static`s can't 219 | be generic. 220 | - It would allow mixing different critical section implementations in the same program, 221 | which would be unsound. 222 | 223 | ## Minimum Supported Rust Version (MSRV) 224 | 225 | This crate is guaranteed to compile on the following Rust versions: 226 | 227 | - If the `std` feature is not enabled: stable Rust 1.54 and up. 228 | - If the `std` feature is enabled: stable Rust 1.63 and up. 229 | - If the `std` feature and `--cfg loom` are enabled: stable Rust 1.73 and up. 230 | 231 | It might compile with older versions but that may change in any new patch release. 232 | 233 | See [here](docs/msrv.md) for details on how the MSRV may be upgraded. 234 | 235 | ## License 236 | 237 | This work is licensed under either of 238 | 239 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or 240 | ) 241 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 242 | 243 | at your option. 244 | 245 | ## Contribution 246 | 247 | Unless you explicitly state otherwise, any contribution intentionally submitted 248 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 249 | dual licensed as above, without any additional terms or conditions. 250 | 251 | ## Code of Conduct 252 | 253 | Contribution to this crate is organized under the terms of the [Rust Code of 254 | Conduct][CoC], the maintainer of this crate, the [HAL team][team], promises 255 | to intervene to uphold that code of conduct. 256 | 257 | [CoC]: CODE_OF_CONDUCT.md 258 | [team]: https://github.com/rust-embedded/wg#the-hal-team 259 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(feature = "std"), no_std)] 2 | #![doc = include_str!("../README.md")] 3 | 4 | mod mutex; 5 | #[cfg(feature = "std")] 6 | mod std; 7 | 8 | use core::marker::PhantomData; 9 | 10 | pub use self::mutex::Mutex; 11 | 12 | /// Critical section token. 13 | /// 14 | /// An instance of this type indicates that the current thread is executing code within a critical 15 | /// section. 16 | #[derive(Clone, Copy, Debug)] 17 | pub struct CriticalSection<'cs> { 18 | _private: PhantomData<&'cs ()>, 19 | 20 | // Prevent CriticalSection from being Send or Sync 21 | // https://github.com/rust-embedded/critical-section/issues/55 22 | _not_send_sync: PhantomData<*mut ()>, 23 | } 24 | 25 | impl<'cs> CriticalSection<'cs> { 26 | /// Creates a critical section token. 27 | /// 28 | /// This method is meant to be used to create safe abstractions rather than being directly used 29 | /// in applications. 30 | /// 31 | /// # Safety 32 | /// 33 | /// This must only be called when the current thread is in a critical section. The caller must 34 | /// ensure that the returned instance will not live beyond the end of the critical section. 35 | /// 36 | /// The caller must use adequate fences to prevent the compiler from moving the 37 | /// instructions inside the critical section to the outside of it. Sequentially consistent fences are 38 | /// suggested immediately after entry and immediately before exit from the critical section. 39 | /// 40 | /// Note that the lifetime `'cs` of the returned instance is unconstrained. User code must not 41 | /// be able to influence the lifetime picked for this type, since that might cause it to be 42 | /// inferred to `'static`. 43 | #[inline(always)] 44 | pub unsafe fn new() -> Self { 45 | CriticalSection { 46 | _private: PhantomData, 47 | _not_send_sync: PhantomData, 48 | } 49 | } 50 | } 51 | 52 | #[cfg(any( 53 | all(feature = "restore-state-none", feature = "restore-state-bool"), 54 | all(feature = "restore-state-none", feature = "restore-state-u8"), 55 | all(feature = "restore-state-none", feature = "restore-state-u16"), 56 | all(feature = "restore-state-none", feature = "restore-state-u32"), 57 | all(feature = "restore-state-none", feature = "restore-state-u64"), 58 | all(feature = "restore-state-bool", feature = "restore-state-u8"), 59 | all(feature = "restore-state-bool", feature = "restore-state-u16"), 60 | all(feature = "restore-state-bool", feature = "restore-state-u32"), 61 | all(feature = "restore-state-bool", feature = "restore-state-u64"), 62 | all(feature = "restore-state-bool", feature = "restore-state-usize"), 63 | all(feature = "restore-state-u8", feature = "restore-state-u16"), 64 | all(feature = "restore-state-u8", feature = "restore-state-u32"), 65 | all(feature = "restore-state-u8", feature = "restore-state-u64"), 66 | all(feature = "restore-state-u8", feature = "restore-state-usize"), 67 | all(feature = "restore-state-u16", feature = "restore-state-u32"), 68 | all(feature = "restore-state-u16", feature = "restore-state-u64"), 69 | all(feature = "restore-state-u16", feature = "restore-state-usize"), 70 | all(feature = "restore-state-u32", feature = "restore-state-u64"), 71 | all(feature = "restore-state-u32", feature = "restore-state-usize"), 72 | all(feature = "restore-state-u64", feature = "restore-state-usize"), 73 | ))] 74 | compile_error!("You must set at most one of these Cargo features: restore-state-none, restore-state-bool, restore-state-u8, restore-state-u16, restore-state-u32, restore-state-u64, restore-state-usize"); 75 | 76 | #[cfg(not(any( 77 | feature = "restore-state-bool", 78 | feature = "restore-state-u8", 79 | feature = "restore-state-u16", 80 | feature = "restore-state-u32", 81 | feature = "restore-state-u64", 82 | feature = "restore-state-usize" 83 | )))] 84 | type RawRestoreStateInner = (); 85 | 86 | #[cfg(feature = "restore-state-bool")] 87 | type RawRestoreStateInner = bool; 88 | 89 | #[cfg(feature = "restore-state-u8")] 90 | type RawRestoreStateInner = u8; 91 | 92 | #[cfg(feature = "restore-state-u16")] 93 | type RawRestoreStateInner = u16; 94 | 95 | #[cfg(feature = "restore-state-u32")] 96 | type RawRestoreStateInner = u32; 97 | 98 | #[cfg(feature = "restore-state-u64")] 99 | type RawRestoreStateInner = u64; 100 | 101 | #[cfg(feature = "restore-state-usize")] 102 | type RawRestoreStateInner = usize; 103 | 104 | // We have RawRestoreStateInner and RawRestoreState so that we don't have to copypaste the docs 5 times. 105 | // In the docs this shows as `pub type RawRestoreState = u8` or whatever the selected type is, because 106 | // the "inner" type alias is private. 107 | 108 | /// Raw, transparent "restore state". 109 | /// 110 | /// This type changes based on which Cargo feature is selected, out of 111 | /// - `restore-state-none` (default, makes the type be `()`) 112 | /// - `restore-state-bool` 113 | /// - `restore-state-u8` 114 | /// - `restore-state-u16` 115 | /// - `restore-state-u32` 116 | /// - `restore-state-u64` 117 | /// - `restore-state-usize` 118 | /// 119 | /// See [`RestoreState`]. 120 | /// 121 | /// User code uses [`RestoreState`] opaquely, critical section implementations 122 | /// use [`RawRestoreState`] so that they can use the inner value. 123 | pub type RawRestoreState = RawRestoreStateInner; 124 | 125 | /// Opaque "restore state". 126 | /// 127 | /// Implementations use this to "carry over" information between acquiring and releasing 128 | /// a critical section. For example, when nesting two critical sections of an 129 | /// implementation that disables interrupts globally, acquiring the inner one won't disable 130 | /// the interrupts since they're already disabled. The impl would use the restore state to "tell" 131 | /// the corresponding release that it does *not* have to reenable interrupts yet, only the 132 | /// outer release should do so. 133 | /// 134 | /// User code uses [`RestoreState`] opaquely, critical section implementations 135 | /// use [`RawRestoreState`] so that they can use the inner value. 136 | #[derive(Clone, Copy, Debug)] 137 | pub struct RestoreState(RawRestoreState); 138 | 139 | impl RestoreState { 140 | /// Create an invalid, dummy `RestoreState`. 141 | /// 142 | /// This can be useful to avoid `Option` when storing a `RestoreState` in a 143 | /// struct field, or a `static`. 144 | /// 145 | /// Note that due to the safety contract of [`acquire`]/[`release`], you must not pass 146 | /// a `RestoreState` obtained from this method to [`release`]. 147 | pub const fn invalid() -> Self { 148 | #[cfg(not(any( 149 | feature = "restore-state-bool", 150 | feature = "restore-state-u8", 151 | feature = "restore-state-u16", 152 | feature = "restore-state-u32", 153 | feature = "restore-state-u64", 154 | feature = "restore-state-usize" 155 | )))] 156 | return Self(()); 157 | 158 | #[cfg(feature = "restore-state-bool")] 159 | return Self(false); 160 | 161 | #[cfg(feature = "restore-state-u8")] 162 | return Self(0); 163 | 164 | #[cfg(feature = "restore-state-u16")] 165 | return Self(0); 166 | 167 | #[cfg(feature = "restore-state-u32")] 168 | return Self(0); 169 | 170 | #[cfg(feature = "restore-state-u64")] 171 | return Self(0); 172 | 173 | #[cfg(feature = "restore-state-usize")] 174 | return Self(0); 175 | } 176 | } 177 | 178 | /// Acquire a critical section in the current thread. 179 | /// 180 | /// This function is extremely low level. Strongly prefer using [`with`] instead. 181 | /// 182 | /// Nesting critical sections is allowed. The inner critical sections 183 | /// are mostly no-ops since they're already protected by the outer one. 184 | /// 185 | /// # Safety 186 | /// 187 | /// - Each `acquire` call must be paired with exactly one `release` call in the same thread. 188 | /// - `acquire` returns a "restore state" that you must pass to the corresponding `release` call. 189 | /// - `acquire`/`release` pairs must be "properly nested", ie it's not OK to do `a=acquire(); b=acquire(); release(a); release(b);`. 190 | /// - It is UB to call `release` if the critical section is not acquired in the current thread. 191 | /// - It is UB to call `release` with a "restore state" that does not come from the corresponding `acquire` call. 192 | /// - It must provide ordering guarantees at least equivalent to a [`core::sync::atomic::Ordering::Acquire`] 193 | /// on a memory location shared by all critical sections, on which the `release` call will do a 194 | /// [`core::sync::atomic::Ordering::Release`] operation. 195 | #[inline(always)] 196 | pub unsafe fn acquire() -> RestoreState { 197 | extern "Rust" { 198 | fn _critical_section_1_0_acquire() -> RawRestoreState; 199 | } 200 | 201 | #[allow(clippy::unit_arg)] 202 | RestoreState(_critical_section_1_0_acquire()) 203 | } 204 | 205 | /// Release the critical section. 206 | /// 207 | /// This function is extremely low level. Strongly prefer using [`with`] instead. 208 | /// 209 | /// # Safety 210 | /// 211 | /// See [`acquire`] for the safety contract description. 212 | #[inline(always)] 213 | pub unsafe fn release(restore_state: RestoreState) { 214 | extern "Rust" { 215 | fn _critical_section_1_0_release(restore_state: RawRestoreState); 216 | } 217 | 218 | #[allow(clippy::unit_arg)] 219 | _critical_section_1_0_release(restore_state.0) 220 | } 221 | 222 | /// Execute closure `f` in a critical section. 223 | /// 224 | /// Nesting critical sections is allowed. The inner critical sections 225 | /// are mostly no-ops since they're already protected by the outer one. 226 | /// 227 | /// # Panics 228 | /// 229 | /// This function panics if the given closure `f` panics. In this case 230 | /// the critical section is released before unwinding. 231 | #[inline] 232 | pub fn with(f: impl FnOnce(CriticalSection) -> R) -> R { 233 | // Helper for making sure `release` is called even if `f` panics. 234 | struct Guard { 235 | state: RestoreState, 236 | } 237 | 238 | impl Drop for Guard { 239 | #[inline(always)] 240 | fn drop(&mut self) { 241 | unsafe { release(self.state) } 242 | } 243 | } 244 | 245 | let state = unsafe { acquire() }; 246 | let _guard = Guard { state }; 247 | 248 | unsafe { f(CriticalSection::new()) } 249 | } 250 | 251 | /// Methods required for a critical section implementation. 252 | /// 253 | /// This trait is not intended to be used except when implementing a critical section. 254 | /// 255 | /// # Safety 256 | /// 257 | /// Implementations must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. 258 | pub unsafe trait Impl { 259 | /// Acquire the critical section. 260 | /// 261 | /// # Safety 262 | /// 263 | /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. 264 | unsafe fn acquire() -> RawRestoreState; 265 | 266 | /// Release the critical section. 267 | /// 268 | /// # Safety 269 | /// 270 | /// Callers must uphold the contract specified in [`crate::acquire`] and [`crate::release`]. 271 | unsafe fn release(restore_state: RawRestoreState); 272 | } 273 | 274 | /// Set the critical section implementation. 275 | /// 276 | /// # Example 277 | /// 278 | /// ``` 279 | /// # #[cfg(not(feature = "std"))] // needed for `cargo test --features std` 280 | /// # mod no_std { 281 | /// use critical_section::RawRestoreState; 282 | /// 283 | /// struct MyCriticalSection; 284 | /// critical_section::set_impl!(MyCriticalSection); 285 | /// 286 | /// unsafe impl critical_section::Impl for MyCriticalSection { 287 | /// unsafe fn acquire() -> RawRestoreState { 288 | /// // ... 289 | /// } 290 | /// 291 | /// unsafe fn release(restore_state: RawRestoreState) { 292 | /// // ... 293 | /// } 294 | /// } 295 | /// # } 296 | #[macro_export] 297 | macro_rules! set_impl { 298 | ($t: ty) => { 299 | #[no_mangle] 300 | unsafe fn _critical_section_1_0_acquire() -> $crate::RawRestoreState { 301 | <$t as $crate::Impl>::acquire() 302 | } 303 | #[no_mangle] 304 | unsafe fn _critical_section_1_0_release(restore_state: $crate::RawRestoreState) { 305 | <$t as $crate::Impl>::release(restore_state) 306 | } 307 | }; 308 | } 309 | --------------------------------------------------------------------------------