blob: ab2ec26485fb9ddc1d23fa7b390b1c6da5525ad9 [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 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;
79 WorkerState mWorkerState GUARDED_BY(mWorkerLock) = WorkerState::STOPPED;
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 Naganov0b9c5fe2022-08-08 18:28:36 +000093} // namespace internal
94
95class StreamLogic {
96 public:
97 friend class internal::ThreadController;
98
99 virtual ~StreamLogic() = default;
100
101 protected:
102 enum class Status { ABORT, CONTINUE, EXIT };
103
104 /* Called once at the beginning of the thread loop. Must return
105 * an empty string to enter the thread loop, otherwise the thread loop
106 * exits and the worker switches into the 'error' state, setting
107 * the error to the returned value.
108 */
109 virtual std::string init() = 0;
110
111 /* Called for each thread loop unless the thread is in 'paused' state.
112 * Must return 'CONTINUE' to continue running, otherwise the thread loop
113 * exits. If the result from worker cycle is 'ABORT' then the worker switches
114 * into the 'error' state with a generic error message. It is recommended that
115 * the subclass reports any problems via logging facilities. Returning the 'EXIT'
116 * status is equivalent to calling 'stop()' method. This is just a way of
117 * of stopping the worker by its own initiative.
118 */
119 virtual Status cycle() = 0;
120};
121
122template <class LogicImpl>
123class StreamWorker : public LogicImpl {
124 public:
125 template <class... Args>
126 explicit StreamWorker(Args&&... args) : LogicImpl(std::forward<Args>(args)...), mThread(this) {}
127
128 // Methods of LogicImpl are available via inheritance.
129 // Forwarded methods of ThreadController follow.
130
131 // Note that 'priority' here is what is known as the 'nice number' in *nix systems.
132 // The nice number is used with the default scheduler. For threads that
133 // need to use a specialized scheduler (e.g. SCHED_FIFO) and set the priority within it,
134 // it is recommended to implement an appropriate configuration sequence within
135 // 'LogicImpl' or 'StreamLogic::init'.
136 bool start(const std::string& name = "", int priority = ANDROID_PRIORITY_DEFAULT) {
137 return mThread.start(name, priority);
138 }
139 void pause() { mThread.pause(); }
140 void resume() { mThread.resume(); }
141 bool hasError() { return mThread.hasError(); }
142 std::string getError() { return mThread.getError(); }
Mikhail Naganov70529732022-10-20 01:16:34 +0000143 void stop() { mThread.stop(); }
144 void join() { mThread.join(); }
Mikhail Naganov0b9c5fe2022-08-08 18:28:36 +0000145 bool waitForAtLeastOneCycle() { return mThread.waitForAtLeastOneCycle(); }
146
147 // Only used by unit tests.
148 void testLockUnlockMutex(bool lock) { mThread.lockUnlockMutex(lock); }
149 std::thread::native_handle_type testGetThreadNativeHandle() {
150 return mThread.getThreadNativeHandle();
151 }
152
153 private:
154 // The ThreadController gets destroyed before LogicImpl.
155 // After the controller has been destroyed, it is guaranteed that
156 // the thread was joined, thus the 'cycle' method of LogicImpl
157 // will not be called anymore, and it is safe to destroy LogicImpl.
158 internal::ThreadController mThread;
159};
160
Mikhail Naganov48d31152022-07-30 00:10:52 +0000161} // namespace android::hardware::audio::common