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