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/assert.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()32inline 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 == reinterpret_cast<SemaphoreHandle_t>(&native_type_)); 37 } 38 ~Mutex()39inline Mutex::~Mutex() { 40 vSemaphoreDelete(reinterpret_cast<SemaphoreHandle_t>(&native_type_)); 41 } 42 lock()43inline void Mutex::lock() { 44 // Enforce the pw::sync::Mutex IRQ contract. 45 PW_DASSERT(!interrupt::InInterruptContext()); 46 #if INCLUDE_vTaskSuspend == 1 // This means portMAX_DELAY is indefinite. 47 const BaseType_t result = xSemaphoreTake( 48 reinterpret_cast<SemaphoreHandle_t>(&native_type_), portMAX_DELAY); 49 PW_DASSERT(result == pdTRUE); 50 #else 51 // In case we need to block for longer than the FreeRTOS delay can represent 52 // repeatedly hit take until success. 53 while (xSemaphoreTake(reinterpret_cast<SemaphoreHandle_t>(&native_type_), 54 chrono::freertos::kMaxTimeout.count()) == pdFALSE) { 55 } 56 #endif // INCLUDE_vTaskSuspend 57 } 58 try_lock()59inline bool Mutex::try_lock() { 60 // Enforce the pw::sync::Mutex IRQ contract. 61 PW_DASSERT(!interrupt::InInterruptContext()); 62 return xSemaphoreTake(reinterpret_cast<SemaphoreHandle_t>(&native_type_), 63 0) == pdTRUE; 64 } 65 unlock()66inline void Mutex::unlock() { 67 // Enforce the pw::sync::Mutex IRQ contract. 68 PW_DASSERT(!interrupt::InInterruptContext()); 69 // Unlocking only fails if it was not locked first. 70 PW_ASSERT(xSemaphoreGive( 71 reinterpret_cast<SemaphoreHandle_t>(&native_type_)) == pdTRUE); 72 } 73 native_handle()74inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; } 75 76 } // namespace pw::sync 77