blob: e9c10704419a04d201ad6f9fe0373d50f310cbf6 [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 Naganove467e012022-12-02 23:46:32 +000035 enum class WorkerState { INITIAL, 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 Naganovcce8e5f2022-09-13 01:20:45 +000042 // Note: 'pause' and 'resume' methods should only be used on the "driving" side.
43 // In the case of audio HAL I/O, the driving side is the client, because the HAL
44 // implementation always blocks on getting a command.
Mikhail Naganov614e4b52022-06-30 21:05:11 +000045 void pause() { switchWorkerStateSync(WorkerState::RUNNING, WorkerState::PAUSE_REQUESTED); }
46 void resume() { switchWorkerStateSync(WorkerState::PAUSED, WorkerState::RESUME_REQUESTED); }
47 bool hasError() {
48 std::lock_guard<std::mutex> lock(mWorkerLock);
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000049 return !mError.empty();
50 }
51 std::string getError() {
52 std::lock_guard<std::mutex> lock(mWorkerLock);
53 return mError;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000054 }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000055 void stop();
Mikhail Naganov70529732022-10-20 01:16:34 +000056 // Direct use of 'join' assumes that the StreamLogic is not intended
57 // to run forever, and is guaranteed to exit by itself. This normally
58 // only happen in tests.
59 void join();
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000060 bool waitForAtLeastOneCycle();
61
Mikhail Naganov0c174e92022-07-21 00:21:08 +000062 // Only used by unit tests.
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000063 void lockUnlockMutex(bool lock) NO_THREAD_SAFETY_ANALYSIS {
Mikhail Naganov0c174e92022-07-21 00:21:08 +000064 lock ? mWorkerLock.lock() : mWorkerLock.unlock();
65 }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000066 std::thread::native_handle_type getThreadNativeHandle() { return mWorker.native_handle(); }
Mikhail Naganov614e4b52022-06-30 21:05:11 +000067
68 private:
69 void switchWorkerStateSync(WorkerState oldState, WorkerState newState,
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000070 WorkerState* finalState = nullptr);
71 void workerThread();
Mikhail Naganov614e4b52022-06-30 21:05:11 +000072
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000073 StreamLogic* const mLogic;
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000074 std::string mThreadName;
75 int mThreadPriority = ANDROID_PRIORITY_DEFAULT;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000076 std::thread mWorker;
77 std::mutex mWorkerLock;
78 std::condition_variable mWorkerCv;
Mikhail Naganove467e012022-12-02 23:46:32 +000079 WorkerState mWorkerState GUARDED_BY(mWorkerLock) = WorkerState::INITIAL;
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000080 std::string mError GUARDED_BY(mWorkerLock);
Mikhail Naganov0c174e92022-07-21 00:21:08 +000081 // The atomic lock-free variable is used to prevent priority inversions
82 // that can occur when a high priority worker tries to acquire the lock
83 // which has been taken by a lower priority control thread which in its turn
84 // got preempted. To prevent a PI under normal operating conditions, that is,
85 // when there are no errors or state changes, the worker does not attempt
86 // taking `mWorkerLock` unless `mWorkerStateChangeRequest` is set.
87 // To make sure that updates to `mWorkerState` and `mWorkerStateChangeRequest`
88 // are serialized, they are always made under a lock.
89 static_assert(std::atomic<bool>::is_always_lock_free);
90 std::atomic<bool> mWorkerStateChangeRequest GUARDED_BY(mWorkerLock) = false;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000091};
Mikhail Naganov48d31152022-07-30 00:10:52 +000092
Mikhail Naganove467e012022-12-02 23:46:32 +000093// A special thread name used in tests only.
94static const std::string kTestSingleThread = "__testST__";
95
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000096} // namespace internal
97
98class StreamLogic {
99 public:
100 friend class internal::ThreadController;
101
102 virtual ~StreamLogic() = default;
103
104 protected:
105 enum class Status { ABORT, CONTINUE, EXIT };
106
107 /* Called once at the beginning of the thread loop. Must return
108 * an empty string to enter the thread loop, otherwise the thread loop
109 * exits and the worker switches into the 'error' state, setting
110 * the error to the returned value.
111 */
112 virtual std::string init() = 0;
113
114 /* Called for each thread loop unless the thread is in 'paused' state.
115 * Must return 'CONTINUE' to continue running, otherwise the thread loop
116 * exits. If the result from worker cycle is 'ABORT' then the worker switches
117 * into the 'error' state with a generic error message. It is recommended that
118 * the subclass reports any problems via logging facilities. Returning the 'EXIT'
119 * status is equivalent to calling 'stop()' method. This is just a way of
120 * of stopping the worker by its own initiative.
121 */
122 virtual Status cycle() = 0;
123};
124
125template <class LogicImpl>
126class StreamWorker : public LogicImpl {
127 public:
128 template <class... Args>
129 explicit StreamWorker(Args&&... args) : LogicImpl(std::forward<Args>(args)...), mThread(this) {}
130
131 // Methods of LogicImpl are available via inheritance.
132 // Forwarded methods of ThreadController follow.
133
134 // Note that 'priority' here is what is known as the 'nice number' in *nix systems.
135 // The nice number is used with the default scheduler. For threads that
136 // need to use a specialized scheduler (e.g. SCHED_FIFO) and set the priority within it,
137 // it is recommended to implement an appropriate configuration sequence within
138 // 'LogicImpl' or 'StreamLogic::init'.
139 bool start(const std::string& name = "", int priority = ANDROID_PRIORITY_DEFAULT) {
140 return mThread.start(name, priority);
141 }
142 void pause() { mThread.pause(); }
143 void resume() { mThread.resume(); }
144 bool hasError() { return mThread.hasError(); }
145 std::string getError() { return mThread.getError(); }
Mikhail Naganov70529732022-10-20 01:16:34 +0000146 void stop() { mThread.stop(); }
147 void join() { mThread.join(); }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +0000148 bool waitForAtLeastOneCycle() { return mThread.waitForAtLeastOneCycle(); }
149
150 // Only used by unit tests.
151 void testLockUnlockMutex(bool lock) { mThread.lockUnlockMutex(lock); }
152 std::thread::native_handle_type testGetThreadNativeHandle() {
153 return mThread.getThreadNativeHandle();
154 }
155
156 private:
157 // The ThreadController gets destroyed before LogicImpl.
158 // After the controller has been destroyed, it is guaranteed that
159 // the thread was joined, thus the 'cycle' method of LogicImpl
160 // will not be called anymore, and it is safe to destroy LogicImpl.
161 internal::ThreadController mThread;
162};
163
Mikhail Naganov48d31152022-07-30 00:10:52 +0000164} // namespace android::hardware::audio::common