1 /*
2 * Copyright (C) 2016 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 <type_traits>
18
19 extern "C" {
20
21 #include "HAP_farf.h"
22 #include "qurt.h"
23 #include "timer.h"
24
25 } // extern "C"
26
27 #include "chre/core/event_loop.h"
28 #include "chre/core/event_loop_manager.h"
29 #include "chre/core/init.h"
30 #include "chre/core/static_nanoapps.h"
31 #include "chre/platform/fatal_error.h"
32 #include "chre/platform/log.h"
33 #include "chre/platform/memory.h"
34 #include "chre/platform/mutex.h"
35 #include "chre/platform/slpi/fastrpc.h"
36 #include "chre/platform/slpi/uimg_util.h"
37 #include "chre/util/lock_guard.h"
38
39 #ifdef CHRE_SLPI_SEE
40 #include "chre/platform/slpi/see/island_vote_client.h"
41 #endif
42
43 #ifdef CHRE_USE_BUFFERED_LOGGING
44 #include "chre/platform/shared/log_buffer_manager.h"
45 #endif
46
47 using chre::EventLoop;
48 using chre::EventLoopManagerSingleton;
49 using chre::LockGuard;
50 using chre::Mutex;
51 using chre::UniquePtr;
52
53 extern "C" int chre_slpi_stop_thread(void);
54
55 // Qualcomm-defined function needed to indicate that the CHRE thread may call
56 // dlopen() (without it, the thread will deadlock when calling dlopen()). Not in
57 // any header file in the SLPI tree or Hexagon SDK (3.0), so declaring here.
58 // Returns 0 to indicate success.
59 extern "C" int HAP_thread_migrate(qurt_thread_t thread);
60
61 namespace {
62
63 //! Size of the stack for the CHRE thread, in bytes.
64 constexpr size_t kStackSize = (8 * 1024);
65
66 //! Memory partition where the thread control block (TCB) should be stored,
67 //! which controls micro-image support.
68 //! @see qurt_thread_attr_set_tcb_partition
69 constexpr unsigned char kTcbPartition =
70 chre::isSlpiUimgSupported() ? QURT_THREAD_ATTR_TCB_PARTITION_TCM
71 : QURT_THREAD_ATTR_TCB_PARTITION_RAM;
72
73 //! The priority to set for the CHRE thread (value between 1-255, with 1 being
74 //! the highest).
75 //! @see qurt_thread_attr_set_priority
76 constexpr unsigned short kThreadPriority = 192;
77
78 //! How long we wait (in microseconds) between checks on whether the CHRE thread
79 //! has exited after we invoked stop().
80 constexpr time_timetick_type kThreadStatusPollingIntervalUsec = 5000; // 5ms
81
82 //! Buffer to use for the CHRE thread's stack.
83 typename std::aligned_storage<kStackSize>::type gStack;
84
85 //! QuRT OS handle for the CHRE thread.
86 qurt_thread_t gThreadHandle;
87
88 //! Protects access to thread metadata, like gThreadRunning, during critical
89 //! sections (starting/stopping the CHRE thread).
90 Mutex gThreadMutex;
91
92 //! Set to true when the CHRE thread starts, and false when it exits normally.
93 bool gThreadRunning;
94
95 //! A thread-local storage key, which is currently only used to add a thread
96 //! destructor callback for the host FastRPC thread.
97 int gTlsKey;
98 bool gTlsKeyValid;
99
100 // TODO(b/181871430): Enable buffered logging for QSH. The QSH implementation
101 // will not log currently.
102
103 #ifdef CHRE_USE_BUFFERED_LOGGING
104
105 //! Primary and secondary log buffers for the LogBufferManager
106 uint8_t gPrimaryLogBufferData[CHRE_LOG_BUFFER_DATA_SIZE];
107 uint8_t gSecondaryLogBufferData[CHRE_LOG_BUFFER_DATA_SIZE];
108
109 #endif
110
111 /**
112 * Entry point for the QuRT thread that runs CHRE.
113 *
114 * @param data Argument passed to qurt_thread_create()
115 */
chreThreadEntry(void *)116 void chreThreadEntry(void * /*data*/) {
117 EventLoopManagerSingleton::get()->lateInit();
118 chre::loadStaticNanoapps();
119 EventLoopManagerSingleton::get()->getEventLoop().run();
120
121 chre::deinit();
122
123 #if defined(CHRE_SLPI_SEE) && !defined(IMPORT_CHRE_UTILS)
124 chre::IslandVoteClientSingleton::deinit();
125 #endif
126 // Perform this as late as possible - if we are shutting down because we
127 // detected exit of the host process, FastRPC will unload us once all our
128 // FastRPC calls have returned. Doing this late helps ensure that the call
129 // to chre_slpi_get_message_to_host() stays open until we're done with
130 // cleanup.
131 chre::HostLinkBase::shutdown();
132 gThreadRunning = false;
133 }
134
onHostProcessTerminated(void *)135 void onHostProcessTerminated(void * /*data*/) {
136 LOGW("Host process died, exiting CHRE (running %d)", gThreadRunning);
137 if (gThreadRunning) {
138 EventLoopManagerSingleton::get()->getEventLoop().stop();
139 }
140 }
141
142 } // anonymous namespace
143
144 namespace chre {
145
inEventLoopThread()146 bool inEventLoopThread() {
147 return (qurt_thread_get_id() == gThreadHandle);
148 }
149
150 } // namespace chre
151
152 /**
153 * Invoked over FastRPC to initialize and start the CHRE thread.
154 *
155 * @return 0 on success, nonzero on failure (per FastRPC requirements)
156 */
chre_slpi_start_thread(void)157 extern "C" int chre_slpi_start_thread(void) {
158 // This lock ensures that we only start the thread once
159 LockGuard<Mutex> lock(gThreadMutex);
160 int fastRpcResult = CHRE_FASTRPC_ERROR;
161
162 #ifdef CHRE_USE_BUFFERED_LOGGING
163 chre::LogBufferManagerSingleton::init(gPrimaryLogBufferData,
164 gSecondaryLogBufferData,
165 sizeof(gPrimaryLogBufferData));
166 #endif
167
168 if (gThreadRunning) {
169 LOGE("CHRE thread already running");
170 } else {
171 #if defined(CHRE_SLPI_SEE) && !defined(IMPORT_CHRE_UTILS)
172 chre::IslandVoteClientSingleton::init("CHRE" /* clientName */);
173 #endif
174
175 // This must complete before we can receive messages that might result in
176 // posting an event
177 chre::init();
178
179 // Human-readable name for the CHRE thread (not const in QuRT API, but they
180 // make a copy)
181 char threadName[] = "CHRE";
182 qurt_thread_attr_t attributes;
183
184 qurt_thread_attr_init(&attributes);
185 qurt_thread_attr_set_name(&attributes, threadName);
186 qurt_thread_attr_set_priority(&attributes, kThreadPriority);
187 qurt_thread_attr_set_stack_addr(&attributes, &gStack);
188 qurt_thread_attr_set_stack_size(&attributes, kStackSize);
189 qurt_thread_attr_set_tcb_partition(&attributes, kTcbPartition);
190
191 gThreadRunning = true;
192 LOGI("Starting CHRE thread");
193 int result = qurt_thread_create(&gThreadHandle, &attributes,
194 chreThreadEntry, nullptr);
195 if (result != QURT_EOK) {
196 LOGE("Couldn't create CHRE thread: %d", result);
197 gThreadRunning = false;
198 } else if (HAP_thread_migrate(gThreadHandle) != 0) {
199 FATAL_ERROR("Couldn't migrate thread");
200 } else {
201 LOGD("Started CHRE thread");
202 fastRpcResult = CHRE_FASTRPC_SUCCESS;
203 }
204 }
205
206 return fastRpcResult;
207 }
208
209 /**
210 * Blocks until the CHRE thread exits. Called over FastRPC to monitor for
211 * abnormal termination of the CHRE thread and/or SLPI as a whole.
212 *
213 * @return Always returns 0, indicating success (per FastRPC requirements)
214 */
chre_slpi_wait_on_thread_exit(void)215 extern "C" int chre_slpi_wait_on_thread_exit(void) {
216 if (!gThreadRunning) {
217 LOGE("Tried monitoring for CHRE thread exit, but thread not running!");
218 } else {
219 int status;
220 int result = qurt_thread_join(gThreadHandle, &status);
221 if (result != QURT_EOK) {
222 LOGE("qurt_thread_join failed with result %d", result);
223 }
224 LOGI("Detected CHRE thread exit");
225 }
226
227 return CHRE_FASTRPC_SUCCESS;
228 }
229
230 /**
231 * If the CHRE thread is running, requests it to perform graceful shutdown,
232 * waits for it to exit, then completes teardown.
233 *
234 * @return Always returns 0, indicating success (per FastRPC requirements)
235 */
chre_slpi_stop_thread(void)236 extern "C" int chre_slpi_stop_thread(void) {
237 // This lock ensures that we will complete shutdown before the thread can be
238 // started again
239 LockGuard<Mutex> lock(gThreadMutex);
240
241 if (!gThreadRunning) {
242 LOGD("Tried to stop CHRE thread, but not running");
243 } else {
244 EventLoopManagerSingleton::get()->getEventLoop().stop();
245 if (gTlsKeyValid) {
246 int ret = qurt_tls_delete_key(gTlsKey);
247 if (ret != QURT_EOK) {
248 // Note: LOGE is not necessarily safe to use after stopping CHRE
249 FARF(ERROR, "Deleting TLS key failed: %d", ret);
250 }
251 gTlsKeyValid = false;
252 }
253
254 // Poll until the thread has stopped; note that we can't use
255 // qurt_thread_join() here because chreMonitorThread() will already be
256 // blocking in it, and attempting to join the same target from two threads
257 // is invalid. Technically, we could use a condition variable, but this is
258 // simpler and we don't care too much about being notified right away.
259 while (gThreadRunning) {
260 timer_sleep(kThreadStatusPollingIntervalUsec, T_USEC,
261 true /* non_deferrable */);
262 }
263 gThreadHandle = 0;
264 }
265
266 return CHRE_FASTRPC_SUCCESS;
267 }
268
269 /**
270 * Creates a thread-local storage (TLS) key in QuRT, which we use to inject a
271 * destructor that is called when the current FastRPC thread terminates. This is
272 * used to get a notification when the original FastRPC thread dies for any
273 * reason, so we can stop the CHRE thread.
274 *
275 * Note that this needs to be invoked from a separate thread on the host process
276 * side. It doesn't work if called from a thread that will be blocking inside a
277 * FastRPC call, such as the monitor thread.
278 *
279 * @return 0 on success, nonzero on failure (per FastRPC requirements)
280 */
chre_slpi_initialize_reverse_monitor(void)281 extern "C" int chre_slpi_initialize_reverse_monitor(void) {
282 LockGuard<Mutex> lock(gThreadMutex);
283
284 if (!gTlsKeyValid) {
285 int result = qurt_tls_create_key(&gTlsKey, onHostProcessTerminated);
286 if (result != QURT_EOK) {
287 LOGE("Couldn't create TLS key: %d", result);
288 } else {
289 // We need to set the value to something for the destructor to be invoked
290 result = qurt_tls_set_specific(gTlsKey, &gTlsKey);
291 if (result != QURT_EOK) {
292 LOGE("Couldn't set TLS data: %d", result);
293 qurt_tls_delete_key(gTlsKey);
294 } else {
295 gTlsKeyValid = true;
296 }
297 }
298 }
299
300 return (gTlsKeyValid) ? CHRE_FASTRPC_SUCCESS : CHRE_FASTRPC_ERROR;
301 }
302