Ewout van Bekkum | 660ebba | 2020-11-11 13:40:10 -0800 | [diff] [blame] | 1 | // Copyright 2020 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 | 660ebba | 2020-11-11 13:40:10 -0800 | [diff] [blame] | 16 | |
Wyatt Hepler | f298de4 | 2021-03-19 15:06:36 -0700 | [diff] [blame] | 17 | #include "pw_assert/check.h" |
Ewout van Bekkum | 660ebba | 2020-11-11 13:40:10 -0800 | [diff] [blame] | 18 | #include "pw_interrupt/context.h" |
| 19 | #include "task.h" |
| 20 | |
| 21 | namespace pw::sync { |
| 22 | |
Ewout van Bekkum | 126e011 | 2021-03-12 10:59:49 -0800 | [diff] [blame] | 23 | void InterruptSpinLock::lock() { |
Ewout van Bekkum | 660ebba | 2020-11-11 13:40:10 -0800 | [diff] [blame] | 24 | if (interrupt::InInterruptContext()) { |
| 25 | native_type_.saved_interrupt_mask = taskENTER_CRITICAL_FROM_ISR(); |
| 26 | } else { // Task context |
| 27 | taskENTER_CRITICAL(); |
| 28 | } |
| 29 | // We can't deadlock here so crash instead. |
Ewout van Bekkum | 2fed999 | 2021-11-23 11:49:02 -0800 | [diff] [blame] | 30 | PW_DCHECK(!native_type_.locked, |
| 31 | "Recursive InterruptSpinLock::lock() detected"); |
Ewout van Bekkum | 25fd893 | 2021-06-22 14:26:55 -0700 | [diff] [blame] | 32 | native_type_.locked = true; |
Ewout van Bekkum | 660ebba | 2020-11-11 13:40:10 -0800 | [diff] [blame] | 33 | } |
| 34 | |
Ewout van Bekkum | 126e011 | 2021-03-12 10:59:49 -0800 | [diff] [blame] | 35 | void InterruptSpinLock::unlock() { |
Ewout van Bekkum | 25fd893 | 2021-06-22 14:26:55 -0700 | [diff] [blame] | 36 | native_type_.locked = false; |
Ewout van Bekkum | 660ebba | 2020-11-11 13:40:10 -0800 | [diff] [blame] | 37 | if (interrupt::InInterruptContext()) { |
| 38 | taskEXIT_CRITICAL_FROM_ISR(native_type_.saved_interrupt_mask); |
| 39 | } else { // Task context |
| 40 | taskEXIT_CRITICAL(); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | } // namespace pw::sync |