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/counting_semaphore.h"
22 #include "semphr.h"
23
24 namespace pw::sync {
25
CountingSemaphore()26 inline CountingSemaphore::CountingSemaphore() : native_type_() {
27 const SemaphoreHandle_t handle =
28 xSemaphoreCreateCountingStatic(max(), 0, &native_type_);
29 // This should never fail since the pointer provided was not null and it
30 // should return a pointer to the StaticSemaphore_t.
31 PW_DASSERT(handle == &native_type_);
32 }
33
~CountingSemaphore()34 inline CountingSemaphore::~CountingSemaphore() {
35 vSemaphoreDelete(&native_type_);
36 }
37
acquire()38 inline void CountingSemaphore::acquire() {
39 PW_ASSERT(!interrupt::InInterruptContext());
40 #if INCLUDE_vTaskSuspend == 1 // This means portMAX_DELAY is indefinite.
41 const BaseType_t result = xSemaphoreTake(&native_type_, portMAX_DELAY);
42 PW_DASSERT(result == pdTRUE);
43 #else
44 // In case we need to block for longer than the FreeRTOS delay can represent
45 // repeatedly hit take until success.
46 while (xSemaphoreTake(&native_type_, chrono::freertos::kMaxTimeout.count()) ==
47 pdFALSE) {
48 }
49 #endif // INCLUDE_vTaskSuspend
50 }
51
try_acquire()52 inline bool CountingSemaphore::try_acquire() noexcept {
53 if (interrupt::InInterruptContext()) {
54 BaseType_t woke_higher_task = pdFALSE;
55 const bool success =
56 xSemaphoreTakeFromISR(&native_type_, &woke_higher_task) == pdTRUE;
57 portYIELD_FROM_ISR(woke_higher_task);
58 return success;
59 }
60
61 // Task Context
62 return xSemaphoreTake(&native_type_, 0) == pdTRUE;
63 }
64
try_acquire_until(chrono::SystemClock::time_point until_at_least)65 inline bool CountingSemaphore::try_acquire_until(
66 chrono::SystemClock::time_point until_at_least) {
67 // Note that if this deadline is in the future, it will get rounded up by
68 // one whole tick due to how try_acquire_for is implemented.
69 return try_acquire_for(until_at_least - chrono::SystemClock::now());
70 }
71
72 inline CountingSemaphore::native_handle_type
native_handle()73 CountingSemaphore::native_handle() {
74 return native_type_;
75 }
76
77 } // namespace pw::sync
78