blob: a82b602f7092d7221b4a40470533681d786dc6ee [file] [log] [blame]
Ewout van Bekkum660ebba2020-11-11 13:40:10 -08001// 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 Bekkum126e0112021-03-12 10:59:49 -080015#include "pw_sync/interrupt_spin_lock.h"
Ewout van Bekkum660ebba2020-11-11 13:40:10 -080016
Wyatt Heplerf298de42021-03-19 15:06:36 -070017#include "pw_assert/check.h"
Ewout van Bekkum660ebba2020-11-11 13:40:10 -080018#include "pw_interrupt/context.h"
19#include "task.h"
20
21namespace pw::sync {
22
Ewout van Bekkum126e0112021-03-12 10:59:49 -080023void InterruptSpinLock::lock() {
Ewout van Bekkum660ebba2020-11-11 13:40:10 -080024 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 Bekkum2fed9992021-11-23 11:49:02 -080030 PW_DCHECK(!native_type_.locked,
31 "Recursive InterruptSpinLock::lock() detected");
Ewout van Bekkum25fd8932021-06-22 14:26:55 -070032 native_type_.locked = true;
Ewout van Bekkum660ebba2020-11-11 13:40:10 -080033}
34
Ewout van Bekkum126e0112021-03-12 10:59:49 -080035void InterruptSpinLock::unlock() {
Ewout van Bekkum25fd8932021-06-22 14:26:55 -070036 native_type_.locked = false;
Ewout van Bekkum660ebba2020-11-11 13:40:10 -080037 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