Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_sync_freertos / public / pw_sync_freertos / mutex_inline.h
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 #pragma once
15
16 #include "FreeRTOS.h"
17 #include "pw_assert/light.h"
18 #include "pw_chrono/system_clock.h"
19 #include "pw_chrono_freertos/system_clock_constants.h"
20 #include "pw_interrupt/context.h"
21 #include "pw_sync/mutex.h"
22 #include "semphr.h"
23
24 namespace pw::sync {
25
26 inline Mutex::Mutex() : native_type_() {
27   native_type_.handle = xSemaphoreCreateMutexStatic(&native_type_.buffer);
28   // This should never fail since the pointer provided was not null.
29   PW_DASSERT(native_type_.handle != nullptr);
30 }
31
32 inline Mutex::~Mutex() { vSemaphoreDelete(&native_type_); }
33
34 inline void Mutex::lock() {
35   PW_ASSERT(!interrupt::InInterruptContext());
36 #if INCLUDE_vTaskSuspend == 1  // This means portMAX_DELAY is indefinite.
37   const BaseType_t result = xSemaphoreTake(native_type_.handle, portMAX_DELAY);
38   PW_DASSERT(result == pdTRUE);
39 #else
40   // In case we need to block for longer than the FreeRTOS delay can represent
41   // repeatedly hit take until success.
42   while (xSemaphoreTake(native_type_.handle,
43                         chrono::freertos::kMaxTimeout.count()) == pdFALSE) {
44   }
45 #endif  // INCLUDE_vTaskSuspend
46 }
47
48 inline bool Mutex::try_lock() {
49   PW_ASSERT(!interrupt::InInterruptContext());
50   return xSemaphoreTake(native_type_.handle, 0) == pdTRUE;
51 }
52
53 inline bool Mutex::try_lock_until(
54     chrono::SystemClock::time_point until_at_least) {
55   return try_lock_for(until_at_least - chrono::SystemClock::now());
56 }
57
58 inline void Mutex::unlock() {
59   PW_ASSERT(!interrupt::InInterruptContext());
60   // Unlocking only fails if it was not locked first.
61   PW_ASSERT(xSemaphoreGive(native_type_.handle) == pdTRUE);
62 }
63
64 inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; }
65
66 }  // namespace pw::sync