blob: 6260eca49a1f738df945dd95534e7a8ef917df14 [file] [log] [blame]
Mikhail Naganov614e4b52022-06-30 21:05:11 +00001/*
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#pragma once
18
Mikhail Naganov0c174e92022-07-21 00:21:08 +000019#include <atomic>
Mikhail Naganov614e4b52022-06-30 21:05:11 +000020#include <condition_variable>
21#include <mutex>
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000022#include <string>
Mikhail Naganov614e4b52022-06-30 21:05:11 +000023#include <thread>
24
25#include <android-base/thread_annotations.h>
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000026#include <system/thread_defs.h>
Mikhail Naganov614e4b52022-06-30 21:05:11 +000027
Mikhail Naganov48d31152022-07-30 00:10:52 +000028namespace android::hardware::audio::common {
29
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000030class StreamLogic;
31
32namespace internal {
33
34class ThreadController {
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000035 enum class WorkerState { STOPPED, RUNNING, PAUSE_REQUESTED, PAUSED, RESUME_REQUESTED };
Mikhail Naganov614e4b52022-06-30 21:05:11 +000036
37 public:
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000038 explicit ThreadController(StreamLogic* logic) : mLogic(logic) {}
39 ~ThreadController() { stop(); }
Mikhail Naganov48d31152022-07-30 00:10:52 +000040
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000041 bool start(const std::string& name, int priority);
Mikhail Naganov614e4b52022-06-30 21:05:11 +000042 void pause() { switchWorkerStateSync(WorkerState::RUNNING, WorkerState::PAUSE_REQUESTED); }
43 void resume() { switchWorkerStateSync(WorkerState::PAUSED, WorkerState::RESUME_REQUESTED); }
44 bool hasError() {
45 std::lock_guard<std::mutex> lock(mWorkerLock);
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000046 return !mError.empty();
47 }
48 std::string getError() {
49 std::lock_guard<std::mutex> lock(mWorkerLock);
50 return mError;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000051 }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000052 void stop();
53 bool waitForAtLeastOneCycle();
54
Mikhail Naganov0c174e92022-07-21 00:21:08 +000055 // Only used by unit tests.
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000056 void lockUnlockMutex(bool lock) NO_THREAD_SAFETY_ANALYSIS {
Mikhail Naganov0c174e92022-07-21 00:21:08 +000057 lock ? mWorkerLock.lock() : mWorkerLock.unlock();
58 }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000059 std::thread::native_handle_type getThreadNativeHandle() { return mWorker.native_handle(); }
Mikhail Naganov614e4b52022-06-30 21:05:11 +000060
61 private:
62 void switchWorkerStateSync(WorkerState oldState, WorkerState newState,
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000063 WorkerState* finalState = nullptr);
64 void workerThread();
Mikhail Naganov614e4b52022-06-30 21:05:11 +000065
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000066 StreamLogic* const mLogic;
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000067 std::string mThreadName;
68 int mThreadPriority = ANDROID_PRIORITY_DEFAULT;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000069 std::thread mWorker;
70 std::mutex mWorkerLock;
71 std::condition_variable mWorkerCv;
72 WorkerState mWorkerState GUARDED_BY(mWorkerLock) = WorkerState::STOPPED;
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000073 std::string mError GUARDED_BY(mWorkerLock);
Mikhail Naganov0c174e92022-07-21 00:21:08 +000074 // The atomic lock-free variable is used to prevent priority inversions
75 // that can occur when a high priority worker tries to acquire the lock
76 // which has been taken by a lower priority control thread which in its turn
77 // got preempted. To prevent a PI under normal operating conditions, that is,
78 // when there are no errors or state changes, the worker does not attempt
79 // taking `mWorkerLock` unless `mWorkerStateChangeRequest` is set.
80 // To make sure that updates to `mWorkerState` and `mWorkerStateChangeRequest`
81 // are serialized, they are always made under a lock.
82 static_assert(std::atomic<bool>::is_always_lock_free);
83 std::atomic<bool> mWorkerStateChangeRequest GUARDED_BY(mWorkerLock) = false;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000084};
Mikhail Naganov48d31152022-07-30 00:10:52 +000085
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000086} // namespace internal
87
88class StreamLogic {
89 public:
90 friend class internal::ThreadController;
91
92 virtual ~StreamLogic() = default;
93
94 protected:
95 enum class Status { ABORT, CONTINUE, EXIT };
96
97 /* Called once at the beginning of the thread loop. Must return
98 * an empty string to enter the thread loop, otherwise the thread loop
99 * exits and the worker switches into the 'error' state, setting
100 * the error to the returned value.
101 */
102 virtual std::string init() = 0;
103
104 /* Called for each thread loop unless the thread is in 'paused' state.
105 * Must return 'CONTINUE' to continue running, otherwise the thread loop
106 * exits. If the result from worker cycle is 'ABORT' then the worker switches
107 * into the 'error' state with a generic error message. It is recommended that
108 * the subclass reports any problems via logging facilities. Returning the 'EXIT'
109 * status is equivalent to calling 'stop()' method. This is just a way of
110 * of stopping the worker by its own initiative.
111 */
112 virtual Status cycle() = 0;
113};
114
115template <class LogicImpl>
116class StreamWorker : public LogicImpl {
117 public:
118 template <class... Args>
119 explicit StreamWorker(Args&&... args) : LogicImpl(std::forward<Args>(args)...), mThread(this) {}
120
121 // Methods of LogicImpl are available via inheritance.
122 // Forwarded methods of ThreadController follow.
123
124 // Note that 'priority' here is what is known as the 'nice number' in *nix systems.
125 // The nice number is used with the default scheduler. For threads that
126 // need to use a specialized scheduler (e.g. SCHED_FIFO) and set the priority within it,
127 // it is recommended to implement an appropriate configuration sequence within
128 // 'LogicImpl' or 'StreamLogic::init'.
129 bool start(const std::string& name = "", int priority = ANDROID_PRIORITY_DEFAULT) {
130 return mThread.start(name, priority);
131 }
132 void pause() { mThread.pause(); }
133 void resume() { mThread.resume(); }
134 bool hasError() { return mThread.hasError(); }
135 std::string getError() { return mThread.getError(); }
136 void stop() { return mThread.stop(); }
137 bool waitForAtLeastOneCycle() { return mThread.waitForAtLeastOneCycle(); }
138
139 // Only used by unit tests.
140 void testLockUnlockMutex(bool lock) { mThread.lockUnlockMutex(lock); }
141 std::thread::native_handle_type testGetThreadNativeHandle() {
142 return mThread.getThreadNativeHandle();
143 }
144
145 private:
146 // The ThreadController gets destroyed before LogicImpl.
147 // After the controller has been destroyed, it is guaranteed that
148 // the thread was joined, thus the 'cycle' method of LogicImpl
149 // will not be called anymore, and it is safe to destroy LogicImpl.
150 internal::ThreadController mThread;
151};
152
Mikhail Naganov48d31152022-07-30 00:10:52 +0000153} // namespace android::hardware::audio::common