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_interrupt/context.h"
19 #include "pw_sync/mutex.h"
20 #include "semphr.h"
21 
22 namespace pw::sync {
23 namespace backend {
24 
25 static_assert(configUSE_MUTEXES != 0, "FreeRTOS mutexes aren't enabled.");
26 
27 static_assert(configSUPPORT_STATIC_ALLOCATION != 0,
28               "FreeRTOS static allocations are required for this backend.");
29 
30 }  // namespace backend
31 
Mutex()32 inline Mutex::Mutex() : native_type_() {
33   const SemaphoreHandle_t handle = xSemaphoreCreateMutexStatic(&native_type_);
34   // This should never fail since the pointer provided was not null and it
35   // should return a pointer to the StaticSemaphore_t.
36   PW_DASSERT(handle == &native_type_);
37 }
38 
~Mutex()39 inline Mutex::~Mutex() { vSemaphoreDelete(&native_type_); }
40 
lock()41 inline void Mutex::lock() {
42   PW_ASSERT(!interrupt::InInterruptContext());
43 #if INCLUDE_vTaskSuspend == 1  // This means portMAX_DELAY is indefinite.
44   const BaseType_t result = xSemaphoreTake(&native_type_, portMAX_DELAY);
45   PW_DASSERT(result == pdTRUE);
46 #else
47   // In case we need to block for longer than the FreeRTOS delay can represent
48   // repeatedly hit take until success.
49   while (xSemaphoreTake(&native_type_, chrono::freertos::kMaxTimeout.count()) ==
50          pdFALSE) {
51   }
52 #endif  // INCLUDE_vTaskSuspend
53 }
54 
try_lock()55 inline bool Mutex::try_lock() {
56   PW_ASSERT(!interrupt::InInterruptContext());
57   return xSemaphoreTake(&native_type_, 0) == pdTRUE;
58 }
59 
unlock()60 inline void Mutex::unlock() {
61   PW_ASSERT(!interrupt::InInterruptContext());
62   // Unlocking only fails if it was not locked first.
63   PW_ASSERT(xSemaphoreGive(&native_type_) == pdTRUE);
64 }
65 
native_handle()66 inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; }
67 
68 }  // namespace pw::sync
69