blob: 88235c2893f8b04652bd5716a12f013aa0bfba26 [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();
Mikhail Naganov70529732022-10-20 01:16:34 +000053 // Direct use of 'join' assumes that the StreamLogic is not intended
54 // to run forever, and is guaranteed to exit by itself. This normally
55 // only happen in tests.
56 void join();
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000057 bool waitForAtLeastOneCycle();
58
Mikhail Naganov0c174e92022-07-21 00:21:08 +000059 // Only used by unit tests.
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000060 void lockUnlockMutex(bool lock) NO_THREAD_SAFETY_ANALYSIS {
Mikhail Naganov0c174e92022-07-21 00:21:08 +000061 lock ? mWorkerLock.lock() : mWorkerLock.unlock();
62 }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000063 std::thread::native_handle_type getThreadNativeHandle() { return mWorker.native_handle(); }
Mikhail Naganov614e4b52022-06-30 21:05:11 +000064
65 private:
66 void switchWorkerStateSync(WorkerState oldState, WorkerState newState,
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000067 WorkerState* finalState = nullptr);
68 void workerThread();
Mikhail Naganov614e4b52022-06-30 21:05:11 +000069
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000070 StreamLogic* const mLogic;
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000071 std::string mThreadName;
72 int mThreadPriority = ANDROID_PRIORITY_DEFAULT;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000073 std::thread mWorker;
74 std::mutex mWorkerLock;
75 std::condition_variable mWorkerCv;
76 WorkerState mWorkerState GUARDED_BY(mWorkerLock) = WorkerState::STOPPED;
Mikhail Naganov48e2e8f2022-07-22 00:07:03 +000077 std::string mError GUARDED_BY(mWorkerLock);
Mikhail Naganov0c174e92022-07-21 00:21:08 +000078 // The atomic lock-free variable is used to prevent priority inversions
79 // that can occur when a high priority worker tries to acquire the lock
80 // which has been taken by a lower priority control thread which in its turn
81 // got preempted. To prevent a PI under normal operating conditions, that is,
82 // when there are no errors or state changes, the worker does not attempt
83 // taking `mWorkerLock` unless `mWorkerStateChangeRequest` is set.
84 // To make sure that updates to `mWorkerState` and `mWorkerStateChangeRequest`
85 // are serialized, they are always made under a lock.
86 static_assert(std::atomic<bool>::is_always_lock_free);
87 std::atomic<bool> mWorkerStateChangeRequest GUARDED_BY(mWorkerLock) = false;
Mikhail Naganov614e4b52022-06-30 21:05:11 +000088};
Mikhail Naganov48d31152022-07-30 00:10:52 +000089
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +000090} // namespace internal
91
92class StreamLogic {
93 public:
94 friend class internal::ThreadController;
95
96 virtual ~StreamLogic() = default;
97
98 protected:
99 enum class Status { ABORT, CONTINUE, EXIT };
100
101 /* Called once at the beginning of the thread loop. Must return
102 * an empty string to enter the thread loop, otherwise the thread loop
103 * exits and the worker switches into the 'error' state, setting
104 * the error to the returned value.
105 */
106 virtual std::string init() = 0;
107
108 /* Called for each thread loop unless the thread is in 'paused' state.
109 * Must return 'CONTINUE' to continue running, otherwise the thread loop
110 * exits. If the result from worker cycle is 'ABORT' then the worker switches
111 * into the 'error' state with a generic error message. It is recommended that
112 * the subclass reports any problems via logging facilities. Returning the 'EXIT'
113 * status is equivalent to calling 'stop()' method. This is just a way of
114 * of stopping the worker by its own initiative.
115 */
116 virtual Status cycle() = 0;
117};
118
119template <class LogicImpl>
120class StreamWorker : public LogicImpl {
121 public:
122 template <class... Args>
123 explicit StreamWorker(Args&&... args) : LogicImpl(std::forward<Args>(args)...), mThread(this) {}
124
125 // Methods of LogicImpl are available via inheritance.
126 // Forwarded methods of ThreadController follow.
127
128 // Note that 'priority' here is what is known as the 'nice number' in *nix systems.
129 // The nice number is used with the default scheduler. For threads that
130 // need to use a specialized scheduler (e.g. SCHED_FIFO) and set the priority within it,
131 // it is recommended to implement an appropriate configuration sequence within
132 // 'LogicImpl' or 'StreamLogic::init'.
133 bool start(const std::string& name = "", int priority = ANDROID_PRIORITY_DEFAULT) {
134 return mThread.start(name, priority);
135 }
136 void pause() { mThread.pause(); }
137 void resume() { mThread.resume(); }
138 bool hasError() { return mThread.hasError(); }
139 std::string getError() { return mThread.getError(); }
Mikhail Naganov70529732022-10-20 01:16:34 +0000140 void stop() { mThread.stop(); }
141 void join() { mThread.join(); }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +0000142 bool waitForAtLeastOneCycle() { return mThread.waitForAtLeastOneCycle(); }
143
144 // Only used by unit tests.
145 void testLockUnlockMutex(bool lock) { mThread.lockUnlockMutex(lock); }
146 std::thread::native_handle_type testGetThreadNativeHandle() {
147 return mThread.getThreadNativeHandle();
148 }
149
150 private:
151 // The ThreadController gets destroyed before LogicImpl.
152 // After the controller has been destroyed, it is guaranteed that
153 // the thread was joined, thus the 'cycle' method of LogicImpl
154 // will not be called anymore, and it is safe to destroy LogicImpl.
155 internal::ThreadController mThread;
156};
157
Mikhail Naganov48d31152022-07-30 00:10:52 +0000158} // namespace android::hardware::audio::common