1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "chre/target_platform/condition_variable_base.h"
18 #include "chre/platform/condition_variable.h"
19
20 #include "intc.h"
21
22 namespace chre {
23
conditionVariablTimerCallback(struct rt_timer * rtTimer)24 void ConditionVariableBase::conditionVariablTimerCallback(
25 struct rt_timer *rtTimer) {
26 if (rtTimer != nullptr) {
27 ConditionVariable *cv =
28 static_cast<ConditionVariable *>(rtTimer->private_ptr);
29 cv->isTimedOut = true;
30 cv->notify_one();
31 }
32 }
33
ConditionVariable()34 ConditionVariable::ConditionVariable() {
35 semaphoreHandle = xSemaphoreCreateBinaryStatic(&mSemaphoreBuffer);
36 if (semaphoreHandle == nullptr) {
37 FATAL_ERROR("Failed to create cv semaphore");
38 }
39 }
40
~ConditionVariable()41 ConditionVariable::~ConditionVariable() {
42 if (semaphoreHandle != NULL) {
43 vSemaphoreDelete(semaphoreHandle);
44 }
45 }
46
notify_one()47 void ConditionVariable::notify_one() {
48 if (is_in_isr()) {
49 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
50 xSemaphoreGiveFromISR(semaphoreHandle, &xHigherPriorityTaskWoken);
51 portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
52 } else {
53 xSemaphoreGive(semaphoreHandle);
54 }
55 }
56
wait(Mutex & mutex)57 void ConditionVariable::wait(Mutex &mutex) {
58 mutex.unlock();
59 BaseType_t rc = xSemaphoreTake(semaphoreHandle, portMAX_DELAY);
60 mutex.lock();
61 if (rc == pdFALSE) {
62 LOGE("Semaphore of the condition variable is unavailable.");
63 }
64 }
65
wait_for(Mutex & mutex,Nanoseconds timeout)66 bool ConditionVariable::wait_for(Mutex &mutex, Nanoseconds timeout) {
67 rt_timer_init(&rtSystemTimer,
68 /* func= */ nullptr,
69 /* data= */ this);
70 rt_timer_start(&rtSystemTimer, timeout.toRawNanoseconds(),
71 /* oneShot= */ true);
72 wait(mutex);
73
74 taskENTER_CRITICAL();
75 if (!isTimedOut) {
76 rt_timer_stop(&rtSystemTimer);
77 }
78 taskEXIT_CRITICAL();
79 return isTimedOut;
80 }
81 } // namespace chre
82