1 /*
2 * Copyright 2021 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 "common/message_loop_thread.h"
18
19 #include <sys/syscall.h>
20 #include <unistd.h>
21 #include <thread>
22
23 #include <base/strings/stringprintf.h>
24
25 #include "gd/common/init_flags.h"
26 #include "osi/include/log.h"
27
28 namespace bluetooth {
29
30 namespace common {
31
32 static constexpr int kRealTimeFifoSchedulingPriority = 1;
33
MessageLoopThread(const std::string & thread_name)34 MessageLoopThread::MessageLoopThread(const std::string& thread_name)
35 : MessageLoopThread(thread_name, false) {}
36
MessageLoopThread(const std::string & thread_name,bool is_main)37 MessageLoopThread::MessageLoopThread(const std::string& thread_name,
38 bool is_main)
39 : thread_name_(thread_name),
40 message_loop_(nullptr),
41 run_loop_(nullptr),
42 thread_(nullptr),
43 thread_id_(-1),
44 linux_tid_(-1),
45 weak_ptr_factory_(this),
46 shutting_down_(false),
47 is_main_(is_main),
48 rust_thread_(nullptr) {}
49
~MessageLoopThread()50 MessageLoopThread::~MessageLoopThread() { ShutDown(); }
51
StartUp()52 void MessageLoopThread::StartUp() {
53 if (is_main_ && init_flags::gd_rust_is_enabled()) {
54 rust_thread_ = new ::rust::Box<shim::rust::MessageLoopThread>(
55 shim::rust::main_message_loop_thread_create());
56 auto rust_id =
57 bluetooth::shim::rust::main_message_loop_thread_start(**rust_thread_);
58 thread_id_ = rust_id;
59 linux_tid_ = rust_id;
60 return;
61 }
62
63 std::promise<void> start_up_promise;
64 std::future<void> start_up_future = start_up_promise.get_future();
65 {
66 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
67 if (thread_ != nullptr) {
68 LOG(WARNING) << __func__ << ": thread " << *this << " is already started";
69
70 return;
71 }
72 thread_ = new std::thread(&MessageLoopThread::RunThread, this,
73 std::move(start_up_promise));
74 }
75 start_up_future.wait();
76 }
77
DoInThread(const base::Location & from_here,base::OnceClosure task)78 bool MessageLoopThread::DoInThread(const base::Location& from_here,
79 base::OnceClosure task) {
80 return DoInThreadDelayed(from_here, std::move(task), base::TimeDelta());
81 }
82
DoInThreadDelayed(const base::Location & from_here,base::OnceClosure task,const base::TimeDelta & delay)83 bool MessageLoopThread::DoInThreadDelayed(const base::Location& from_here,
84 base::OnceClosure task,
85 const base::TimeDelta& delay) {
86 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
87 if (is_main_ && init_flags::gd_rust_is_enabled()) {
88 if (rust_thread_ == nullptr) {
89 LOG(ERROR) << __func__ << ": rust thread is null for thread " << *this
90 << ", from " << from_here.ToString();
91 return false;
92 }
93
94 shim::rust::main_message_loop_thread_do_delayed(
95 **rust_thread_,
96 std::make_unique<shim::rust::OnceClosure>(std::move(task)),
97 delay.InMilliseconds());
98 return true;
99 }
100
101 if (message_loop_ == nullptr) {
102 LOG(ERROR) << __func__ << ": message loop is null for thread " << *this
103 << ", from " << from_here.ToString();
104 return false;
105 }
106 if (!message_loop_->task_runner()->PostDelayedTask(from_here, std::move(task),
107 delay)) {
108 LOG(ERROR) << __func__
109 << ": failed to post task to message loop for thread " << *this
110 << ", from " << from_here.ToString();
111 return false;
112 }
113 return true;
114 }
115
ShutDown()116 void MessageLoopThread::ShutDown() {
117 {
118 if (is_main_ && init_flags::gd_rust_is_enabled()) {
119 delete rust_thread_;
120 thread_id_ = -1;
121 linux_tid_ = -1;
122 return;
123 }
124
125 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
126 if (thread_ == nullptr) {
127 LOG(INFO) << __func__ << ": thread " << *this << " is already stopped";
128 return;
129 }
130 if (message_loop_ == nullptr) {
131 LOG(INFO) << __func__ << ": message_loop_ is null. Already stopping";
132 return;
133 }
134 if (shutting_down_) {
135 LOG(INFO) << __func__ << ": waiting for thread to join";
136 return;
137 }
138 shutting_down_ = true;
139 CHECK_NE(thread_id_, base::PlatformThread::CurrentId())
140 << __func__ << " should not be called on the thread itself. "
141 << "Otherwise, deadlock may happen.";
142 if (!message_loop_->task_runner()->PostTask(
143 FROM_HERE, run_loop_->QuitWhenIdleClosure())) {
144 LOG(FATAL) << __func__
145 << ": failed to post task to message loop for thread "
146 << *this;
147 }
148 }
149 thread_->join();
150 {
151 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
152 delete thread_;
153 thread_ = nullptr;
154 shutting_down_ = false;
155 }
156 }
157
GetThreadId() const158 base::PlatformThreadId MessageLoopThread::GetThreadId() const {
159 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
160 return thread_id_;
161 }
162
GetName() const163 std::string MessageLoopThread::GetName() const { return thread_name_; }
164
ToString() const165 std::string MessageLoopThread::ToString() const {
166 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
167 return base::StringPrintf("%s(%d)", thread_name_.c_str(), thread_id_);
168 }
169
IsRunning() const170 bool MessageLoopThread::IsRunning() const {
171 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
172 return thread_id_ != -1;
173 }
174
175 // Non API method, should not be protected by API mutex
RunThread(MessageLoopThread * thread,std::promise<void> start_up_promise)176 void MessageLoopThread::RunThread(MessageLoopThread* thread,
177 std::promise<void> start_up_promise) {
178 thread->Run(std::move(start_up_promise));
179 }
180
message_loop() const181 btbase::AbstractMessageLoop* MessageLoopThread::message_loop() const {
182 ASSERT_LOG(!is_main_,
183 "you are not allowed to get the main thread's message loop");
184
185 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
186 return message_loop_;
187 }
188
EnableRealTimeScheduling()189 bool MessageLoopThread::EnableRealTimeScheduling() {
190 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
191
192 if (!IsRunning()) {
193 LOG(ERROR) << __func__ << ": thread " << *this << " is not running";
194 return false;
195 }
196
197 struct sched_param rt_params = {.sched_priority =
198 kRealTimeFifoSchedulingPriority};
199 int rc = sched_setscheduler(linux_tid_, SCHED_FIFO, &rt_params);
200 if (rc != 0) {
201 LOG(ERROR) << __func__ << ": unable to set SCHED_FIFO priority "
202 << kRealTimeFifoSchedulingPriority << " for linux_tid "
203 << std::to_string(linux_tid_) << ", thread " << *this
204 << ", error: " << strerror(errno);
205 return false;
206 }
207 return true;
208 }
209
GetWeakPtr()210 base::WeakPtr<MessageLoopThread> MessageLoopThread::GetWeakPtr() {
211 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
212 return weak_ptr_factory_.GetWeakPtr();
213 }
214
Run(std::promise<void> start_up_promise)215 void MessageLoopThread::Run(std::promise<void> start_up_promise) {
216 {
217 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
218 if (is_main_ && init_flags::gd_rust_is_enabled()) {
219 return;
220 }
221
222 LOG(INFO) << __func__ << ": message loop starting for thread "
223 << thread_name_;
224 base::PlatformThread::SetName(thread_name_);
225 message_loop_ = new btbase::AbstractMessageLoop();
226 run_loop_ = new base::RunLoop();
227 thread_id_ = base::PlatformThread::CurrentId();
228 linux_tid_ = static_cast<pid_t>(syscall(SYS_gettid));
229 start_up_promise.set_value();
230 }
231
232 // Blocking until ShutDown() is called
233 run_loop_->Run();
234
235 {
236 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
237 thread_id_ = -1;
238 linux_tid_ = -1;
239 delete message_loop_;
240 message_loop_ = nullptr;
241 delete run_loop_;
242 run_loop_ = nullptr;
243 LOG(INFO) << __func__ << ": message loop finished for thread "
244 << thread_name_;
245 }
246 }
247
248 } // namespace common
249
250 } // namespace bluetooth
251