1 /*
2 * Copyright 2018 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 "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 {
164 return thread_name_;
165 }
166
ToString() const167 std::string MessageLoopThread::ToString() const {
168 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
169 return base::StringPrintf("%s(%d)", thread_name_.c_str(), thread_id_);
170 }
171
IsRunning() const172 bool MessageLoopThread::IsRunning() const {
173 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
174 return thread_id_ != -1;
175 }
176
177 // Non API method, should not be protected by API mutex
RunThread(MessageLoopThread * thread,std::promise<void> start_up_promise)178 void MessageLoopThread::RunThread(MessageLoopThread* thread,
179 std::promise<void> start_up_promise) {
180 thread->Run(std::move(start_up_promise));
181 }
182
message_loop() const183 btbase::AbstractMessageLoop* MessageLoopThread::message_loop() const {
184 ASSERT_LOG(!is_main_,
185 "you are not allowed to get the main thread's message loop");
186
187 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
188 return message_loop_;
189 }
190
EnableRealTimeScheduling()191 bool MessageLoopThread::EnableRealTimeScheduling() {
192 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
193
194 if (!IsRunning()) {
195 LOG(ERROR) << __func__ << ": thread " << *this << " is not running";
196 return false;
197 }
198
199 struct sched_param rt_params = {.sched_priority =
200 kRealTimeFifoSchedulingPriority};
201 int rc = sched_setscheduler(linux_tid_, SCHED_FIFO, &rt_params);
202 if (rc != 0) {
203 LOG(ERROR) << __func__ << ": unable to set SCHED_FIFO priority "
204 << kRealTimeFifoSchedulingPriority << " for linux_tid "
205 << std::to_string(linux_tid_) << ", thread " << *this
206 << ", error: " << strerror(errno);
207 return false;
208 }
209 return true;
210 }
211
GetWeakPtr()212 base::WeakPtr<MessageLoopThread> MessageLoopThread::GetWeakPtr() {
213 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
214 return weak_ptr_factory_.GetWeakPtr();
215 }
216
Run(std::promise<void> start_up_promise)217 void MessageLoopThread::Run(std::promise<void> start_up_promise) {
218 {
219 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
220 if (is_main_ && init_flags::gd_rust_is_enabled()) {
221 return;
222 }
223
224 LOG(INFO) << __func__ << ": message loop starting for thread "
225 << thread_name_;
226 base::PlatformThread::SetName(thread_name_);
227 message_loop_ = new btbase::AbstractMessageLoop();
228 run_loop_ = new base::RunLoop();
229 thread_id_ = base::PlatformThread::CurrentId();
230 linux_tid_ = static_cast<pid_t>(syscall(SYS_gettid));
231 start_up_promise.set_value();
232 }
233
234 // Blocking until ShutDown() is called
235 run_loop_->Run();
236
237 {
238 std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
239 thread_id_ = -1;
240 linux_tid_ = -1;
241 delete message_loop_;
242 message_loop_ = nullptr;
243 delete run_loop_;
244 run_loop_ = nullptr;
245 LOG(INFO) << __func__ << ": message loop finished for thread "
246 << thread_name_;
247 }
248 }
249
250 } // namespace common
251
252 } // namespace bluetooth
253