Ewout van Bekkum | 41daf16 | 2021-03-03 13:57:28 -0800 | [diff] [blame] | 1 | // Copyright 2021 The Pigweed Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 4 | // use this file except in compliance with the License. You may obtain a copy of |
| 5 | // the License at |
| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | // License for the specific language governing permissions and limitations under |
| 13 | // the License. |
| 14 | |
Ewout van Bekkum | 126e011 | 2021-03-12 10:59:49 -0800 | [diff] [blame] | 15 | #include "pw_sync/interrupt_spin_lock.h" |
Ewout van Bekkum | 41daf16 | 2021-03-03 13:57:28 -0800 | [diff] [blame] | 16 | |
| 17 | #include "RTOS.h" |
| 18 | #include "pw_assert/assert.h" |
| 19 | |
| 20 | namespace pw::sync { |
| 21 | |
Ewout van Bekkum | 126e011 | 2021-03-12 10:59:49 -0800 | [diff] [blame] | 22 | void InterruptSpinLock::lock() { |
Ewout van Bekkum | 41daf16 | 2021-03-03 13:57:28 -0800 | [diff] [blame] | 23 | OS_IncDI(); |
| 24 | // We can't deadlock here so crash instead. |
| 25 | PW_CHECK(!native_type_.locked.load(std::memory_order_relaxed), |
Ewout van Bekkum | 126e011 | 2021-03-12 10:59:49 -0800 | [diff] [blame] | 26 | "Recursive InterruptSpinLock::lock() detected"); |
Ewout van Bekkum | 41daf16 | 2021-03-03 13:57:28 -0800 | [diff] [blame] | 27 | native_type_.locked.store(true, std::memory_order_relaxed); |
| 28 | } |
| 29 | |
Ewout van Bekkum | 126e011 | 2021-03-12 10:59:49 -0800 | [diff] [blame] | 30 | bool InterruptSpinLock::try_lock() { |
Ewout van Bekkum | 41daf16 | 2021-03-03 13:57:28 -0800 | [diff] [blame] | 31 | OS_IncDI(); |
| 32 | if (native_type_.locked.load(std::memory_order_relaxed)) { |
| 33 | OS_DecRI(); // Already locked, restore interrupts and bail out. |
| 34 | return false; |
| 35 | } |
| 36 | native_type_.locked.store(true, std::memory_order_relaxed); |
| 37 | return true; |
| 38 | } |
| 39 | |
Ewout van Bekkum | 126e011 | 2021-03-12 10:59:49 -0800 | [diff] [blame] | 40 | void InterruptSpinLock::unlock() { |
Ewout van Bekkum | 41daf16 | 2021-03-03 13:57:28 -0800 | [diff] [blame] | 41 | native_type_.locked.store(false, std::memory_order_relaxed); |
| 42 | OS_DecRI(); |
| 43 | } |
| 44 | |
| 45 | } // namespace pw::sync |