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 "qurt.h"
22 
23 }  // extern "C"
24 
25 #include "chre/core/event_loop.h"
26 #include "chre/core/event_loop_manager.h"
27 #include "chre/core/init.h"
28 #include "chre/core/nanoapp.h"
29 #include "chre/platform/log.h"
30 #include "chre/platform/memory.h"
31 #include "chre/platform/mutex.h"
32 #include "chre/platform/platform_nanoapp.h"
33 #include "chre/platform/slpi/fastrpc.h"
34 #include "chre/platform/static_nanoapps.h"
35 #include "chre/util/lock_guard.h"
36 
37 using chre::EventLoop;
38 using chre::LockGuard;
39 using chre::Mutex;
40 
41 extern "C" int chre_slpi_stop_thread(void);
42 
43 namespace {
44 
45 //! Size of the stack for the CHRE thread, in bytes.
46 constexpr size_t kStackSize = (8 * 1024);
47 
48 //! Memory partition where the thread control block (TCB) should be stored,
49 //! which controls micro-image support (0 = big image, 1 = micro image).
50 //! @see qurt_thread_attr_set_tcb_partition
51 constexpr unsigned char kTcbPartition = 0;
52 
53 //! How long we wait (in microseconds) between checks on whether the CHRE thread
54 //! has exited after we invoked stop().
55 constexpr qurt_timer_duration_t kThreadStatusPollingIntervalUsec = 5000;  // 5ms
56 
57 //! Pointer to the main CHRE event loop. Modification must only be done while
58 //! the CHRE thread is stopped, and while holding gThreadMutex.
59 EventLoop *gEventLoop;
60 
61 //! Buffer to use for the CHRE thread's stack.
62 typename std::aligned_storage<kStackSize>::type gStack;
63 
64 //! QuRT OS handle for the CHRE thread.
65 qurt_thread_t gThreadHandle;
66 
67 //! Protects access to thread metadata, like gThreadRunning, during critical
68 //! sections (starting/stopping the CHRE thread).
69 Mutex *gThreadMutex;
70 typename std::aligned_storage<sizeof(Mutex), alignof(Mutex)>::type
71     gThreadMutexStorage;
72 
73 //! Set to true when the CHRE thread starts, and false when it exits normally.
74 bool gThreadRunning;
75 
76 //! A thread-local storage key, which is currently only used to add a thread
77 //! destructor callback for the host FastRPC thread.
78 int gTlsKey;
79 bool gTlsKeyValid;
80 
81 // TODO: We would prefer to just use staitc global C++ constructor/destructor
82 // support, but currently, destructors do not seem to get called. These work as
83 // a temporary workaround, though.
84 __attribute__((constructor))
onLoad(void)85 void onLoad(void) {
86   gThreadMutex = new(&gThreadMutexStorage) Mutex();
87 }
88 
89 __attribute__((destructor))
onUnload(void)90 void onUnload(void) {
91   gThreadMutex->~Mutex();
92   gThreadMutex = nullptr;
93 }
94 
95 /**
96  * Entry point for the QuRT thread that runs CHRE.
97  *
98  * @param data Argument passed to qurt_thread_create()
99  */
chreThreadEntry(void *)100 void chreThreadEntry(void * /*data*/) {
101   chre::init();
102   gEventLoop = chre::EventLoopManagerSingleton::get()->createEventLoop();
103   if (gEventLoop == nullptr) {
104     LOGE("Failed to create event loop!");
105   } else {
106     loadStaticNanoapps(gEventLoop);
107     gEventLoop->run();
108   }
109 
110   chre::deinit();
111   gEventLoop = nullptr;
112   gThreadRunning = false;
113   LOGD("CHRE thread exiting");
114 }
115 
onHostProcessTerminated(void *)116 void onHostProcessTerminated(void * /*data*/) {
117   LOGW("Host process died, exiting CHRE (running %d)", gThreadRunning);
118   chre_slpi_stop_thread();
119 }
120 
121 }  // anonymous namespace
122 
123 namespace chre {
124 
getCurrentEventLoop()125 EventLoop *getCurrentEventLoop() {
126   return (qurt_thread_get_id() == gThreadHandle) ? gEventLoop : nullptr;
127 }
128 
129 }  // namespace chre
130 
131 /**
132  * Invoked over FastRPC to initialize and start the CHRE thread.
133  *
134  * @return 0 on success, nonzero on failure (per FastRPC requirements)
135  */
chre_slpi_start_thread(void)136 extern "C" int chre_slpi_start_thread(void) {
137   // This lock ensures that we only start the thread once
138   LockGuard<Mutex> lock(*gThreadMutex);
139   int fastRpcResult = CHRE_FASTRPC_ERROR;
140 
141   if (gThreadRunning) {
142     LOGE("CHRE thread already running");
143   } else {
144     // Human-readable name for the CHRE thread (not const in QuRT API, but they
145     // make a copy)
146     char threadName[] = "CHRE";
147     qurt_thread_attr_t attributes;
148 
149     qurt_thread_attr_init(&attributes);
150     qurt_thread_attr_set_stack_addr(&attributes, &gStack);
151     qurt_thread_attr_set_stack_size(&attributes, kStackSize);
152     qurt_thread_attr_set_name(&attributes, threadName);
153     qurt_thread_attr_set_tcb_partition(&attributes, kTcbPartition);
154 
155     int result = qurt_thread_create(&gThreadHandle, &attributes,
156                                     chreThreadEntry, nullptr);
157     if (result != QURT_EOK) {
158       LOGE("Couldn't create CHRE thread: %d", result);
159     } else {
160       LOGD("Started CHRE thread");
161       gThreadRunning = true;
162       fastRpcResult = CHRE_FASTRPC_SUCCESS;
163     }
164   }
165 
166   return fastRpcResult;
167 }
168 
169 /**
170  * Blocks until the CHRE thread exits. Called over FastRPC to monitor for
171  * abnormal termination of the CHRE thread and/or SLPI as a whole.
172  *
173  * @return Always returns 0, indicating success (per FastRPC requirements)
174  */
chre_slpi_wait_on_thread_exit(void)175 extern "C" int chre_slpi_wait_on_thread_exit(void) {
176   if (!gThreadRunning) {
177     LOGE("Tried monitoring for CHRE thread exit, but thread not running!");
178   } else {
179     int status;
180     int result = qurt_thread_join(gThreadHandle, &status);
181     if (result != QURT_EOK) {
182       LOGE("qurt_thread_join failed with result %d", result);
183     }
184     LOGI("Detected CHRE thread exit");
185   }
186 
187   return CHRE_FASTRPC_SUCCESS;
188 }
189 
190 /**
191  * If the CHRE thread is running, requests it to perform graceful shutdown,
192  * waits for it to exit, then completes teardown.
193  *
194  * @return Always returns 0, indicating success (per FastRPC requirements)
195  */
chre_slpi_stop_thread(void)196 extern "C" int chre_slpi_stop_thread(void) {
197   // This lock ensures that we will complete shutdown before the thread can be
198   // started again
199   LockGuard<Mutex> lock(*gThreadMutex);
200 
201   if (!gThreadRunning || gEventLoop == nullptr) {
202     LOGD("Tried to stop CHRE thread, but not running");
203   } else {
204     gEventLoop->stop();
205 
206     // Poll until the thread has stopped; note that we can't use
207     // qurt_thread_join() here because chreMonitorThread() will already be
208     // blocking in it, and attempting to join the same target from two threads
209     // is invalid. Technically, we could use a condition variable, but this is
210     // simpler and we don't care too much about being notified right away.
211     while (gThreadRunning) {
212       qurt_timer_sleep(kThreadStatusPollingIntervalUsec);
213     }
214     gThreadHandle = 0;
215 
216     // TODO: need to figure out the right place to put this, to make sure we're
217     // not trying to post events to an EventLoop that is already stopped, etc.
218     // Becomes even trickier when log messages get routed through the HostLink.
219     chre::HostLinkBase::shutdown();
220 
221     if (gTlsKeyValid) {
222       int ret = qurt_tls_delete_key(gTlsKey);
223       if (ret != QURT_EOK) {
224         // Note: LOGE is not necessarily safe to use after stopping CHRE
225         FARF(ERROR, "Deleting TLS key failed: %d", ret);
226       }
227       gTlsKeyValid = false;
228     }
229   }
230 
231   return CHRE_FASTRPC_SUCCESS;
232 }
233 
234 /**
235  * Creates a thread-local storage (TLS) key in QuRT, which we use to inject a
236  * destructor that is called when the current FastRPC thread terminates. This is
237  * used to get a notification when the original FastRPC thread dies for any
238  * reason, so we can stop the CHRE thread.
239  *
240  * Note that this needs to be invoked from a separate thread on the host process
241  * side. It doesn't work if called from a thread that will be blocking inside a
242  * FastRPC call, such as the monitor thread.
243  *
244  * @return 0 on success, nonzero on failure (per FastRPC requirements)
245  */
chre_slpi_initialize_reverse_monitor(void)246 extern "C" int chre_slpi_initialize_reverse_monitor(void) {
247   LockGuard<Mutex> lock(*gThreadMutex);
248 
249   if (!gTlsKeyValid) {
250     int result = qurt_tls_create_key(&gTlsKey, onHostProcessTerminated);
251     if (result != QURT_EOK) {
252       LOGE("Couldn't create TLS key: %d", result);
253     } else {
254       // We need to set the value to something for the destructor to be invoked
255       result = qurt_tls_set_specific(gTlsKey, &gTlsKey);
256       if (result != QURT_EOK) {
257         LOGE("Couldn't set TLS data: %d", result);
258         qurt_tls_delete_key(gTlsKey);
259       } else {
260         gTlsKeyValid = true;
261       }
262     }
263   }
264 
265   return (gTlsKeyValid) ? CHRE_FASTRPC_SUCCESS : CHRE_FASTRPC_ERROR;
266 }
267 
268 // TODO: Remove this stub once the symbol is provided.
__cxa_finalize(void *)269 extern "C" void __cxa_finalize(void *) {}
270