blob: 2bb029cec45dca83c0e8e0f7d6f107641bb2e719 [file] [log] [blame]
Ewout van Bekkum41daf162021-03-03 13:57:28 -08001// 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 Bekkum126e0112021-03-12 10:59:49 -080015#include "pw_sync/interrupt_spin_lock.h"
Ewout van Bekkum41daf162021-03-03 13:57:28 -080016
17#include "RTOS.h"
Wyatt Heplerf298de42021-03-19 15:06:36 -070018#include "pw_assert/check.h"
Ewout van Bekkum41daf162021-03-03 13:57:28 -080019
20namespace pw::sync {
21
Ewout van Bekkum126e0112021-03-12 10:59:49 -080022void InterruptSpinLock::lock() {
Ewout van Bekkum41daf162021-03-03 13:57:28 -080023 OS_IncDI();
24 // We can't deadlock here so crash instead.
25 PW_CHECK(!native_type_.locked.load(std::memory_order_relaxed),
Ewout van Bekkum126e0112021-03-12 10:59:49 -080026 "Recursive InterruptSpinLock::lock() detected");
Ewout van Bekkum41daf162021-03-03 13:57:28 -080027 native_type_.locked.store(true, std::memory_order_relaxed);
28}
29
Ewout van Bekkum126e0112021-03-12 10:59:49 -080030bool InterruptSpinLock::try_lock() {
Ewout van Bekkum41daf162021-03-03 13:57:28 -080031 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 Bekkum126e0112021-03-12 10:59:49 -080040void InterruptSpinLock::unlock() {
Ewout van Bekkum41daf162021-03-03 13:57:28 -080041 native_type_.locked.store(false, std::memory_order_relaxed);
42 OS_DecRI();
43}
44
45} // namespace pw::sync