event_loop.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. #include "chre/core/event_loop.h"
  17. #include "chre/core/event.h"
  18. #include "chre/core/event_loop_manager.h"
  19. #include "chre/core/nanoapp.h"
  20. #include "chre/platform/context.h"
  21. #include "chre/platform/fatal_error.h"
  22. #include "chre/platform/log.h"
  23. #include "chre/platform/system_time.h"
  24. #include "chre/util/conditional_lock_guard.h"
  25. #include "chre/util/lock_guard.h"
  26. #include "chre/util/system/debug_dump.h"
  27. #include "chre/util/time.h"
  28. #include "chre_api/chre/version.h"
  29. namespace chre {
  30. namespace {
  31. /**
  32. * Populates a chreNanoappInfo structure using info from the given Nanoapp
  33. * instance.
  34. *
  35. * @param app A potentially null pointer to the Nanoapp to read from
  36. * @param info The structure to populate - should not be null, but this function
  37. * will handle that input
  38. *
  39. * @return true if neither app nor info were null, and info was populated
  40. */
  41. bool populateNanoappInfo(const Nanoapp *app, struct chreNanoappInfo *info) {
  42. bool success = false;
  43. if (app != nullptr && info != nullptr) {
  44. info->appId = app->getAppId();
  45. info->version = app->getAppVersion();
  46. info->instanceId = app->getInstanceId();
  47. success = true;
  48. }
  49. return success;
  50. }
  51. } // anonymous namespace
  52. bool EventLoop::findNanoappInstanceIdByAppId(uint64_t appId,
  53. uint32_t *instanceId) const {
  54. CHRE_ASSERT(instanceId != nullptr);
  55. ConditionalLockGuard<Mutex> lock(mNanoappsLock, !inEventLoopThread());
  56. bool found = false;
  57. for (const UniquePtr<Nanoapp>& app : mNanoapps) {
  58. if (app->getAppId() == appId) {
  59. *instanceId = app->getInstanceId();
  60. found = true;
  61. break;
  62. }
  63. }
  64. return found;
  65. }
  66. void EventLoop::forEachNanoapp(NanoappCallbackFunction *callback, void *data) {
  67. ConditionalLockGuard<Mutex> lock(mNanoappsLock, !inEventLoopThread());
  68. for (const UniquePtr<Nanoapp>& nanoapp : mNanoapps) {
  69. callback(nanoapp.get(), data);
  70. }
  71. }
  72. void EventLoop::invokeMessageFreeFunction(
  73. uint64_t appId, chreMessageFreeFunction *freeFunction, void *message,
  74. size_t messageSize) {
  75. Nanoapp *nanoapp = lookupAppByAppId(appId);
  76. if (nanoapp == nullptr) {
  77. LOGE("Couldn't find app 0x%016" PRIx64 " for message free callback", appId);
  78. } else {
  79. auto prevCurrentApp = mCurrentApp;
  80. mCurrentApp = nanoapp;
  81. freeFunction(message, messageSize);
  82. mCurrentApp = prevCurrentApp;
  83. }
  84. }
  85. void EventLoop::run() {
  86. LOGI("EventLoop start");
  87. bool havePendingEvents = false;
  88. while (mRunning) {
  89. // Events are delivered in two stages: first they arrive in the inbound
  90. // event queue mEvents (potentially posted from another thread), then within
  91. // this context these events are distributed to smaller event queues
  92. // associated with each Nanoapp that should receive the event. Once the
  93. // event is delivered to all interested Nanoapps, its free callback is
  94. // invoked.
  95. if (!havePendingEvents || !mEvents.empty()) {
  96. if (mEvents.size() > mMaxEventPoolUsage) {
  97. mMaxEventPoolUsage = mEvents.size();
  98. }
  99. // mEvents.pop() will be a blocking call if mEvents.empty()
  100. distributeEvent(mEvents.pop());
  101. }
  102. havePendingEvents = deliverEvents();
  103. mPowerControlManager.postEventLoopProcess(mEvents.size());
  104. }
  105. // Deliver any events sitting in Nanoapps' own queues (we could drop them to
  106. // exit faster, but this is less code and should complete quickly under normal
  107. // conditions), then purge the main queue of events pending distribution. All
  108. // nanoapps should be prevented from sending events or messages at this point
  109. // via currentNanoappIsStopping() returning true.
  110. flushNanoappEventQueues();
  111. while (!mEvents.empty()) {
  112. freeEvent(mEvents.pop());
  113. }
  114. // Unload all running nanoapps
  115. while (!mNanoapps.empty()) {
  116. unloadNanoappAtIndex(mNanoapps.size() - 1);
  117. }
  118. LOGI("Exiting EventLoop");
  119. }
  120. bool EventLoop::startNanoapp(UniquePtr<Nanoapp>& nanoapp) {
  121. CHRE_ASSERT(!nanoapp.isNull());
  122. bool success = false;
  123. auto *eventLoopManager = EventLoopManagerSingleton::get();
  124. EventLoop& eventLoop = eventLoopManager->getEventLoop();
  125. uint32_t existingInstanceId;
  126. if (nanoapp.isNull()) {
  127. // no-op, invalid argument
  128. } else if (eventLoop.findNanoappInstanceIdByAppId(nanoapp->getAppId(),
  129. &existingInstanceId)) {
  130. LOGE("App with ID 0x%016" PRIx64 " already exists as instance ID 0x%"
  131. PRIx32, nanoapp->getAppId(), existingInstanceId);
  132. } else if (!mNanoapps.prepareForPush()) {
  133. LOG_OOM();
  134. } else {
  135. nanoapp->setInstanceId(eventLoopManager->getNextInstanceId());
  136. LOGD("Instance ID %" PRIu32 " assigned to app ID 0x%016" PRIx64,
  137. nanoapp->getInstanceId(), nanoapp->getAppId());
  138. Nanoapp *newNanoapp = nanoapp.get();
  139. {
  140. LockGuard<Mutex> lock(mNanoappsLock);
  141. mNanoapps.push_back(std::move(nanoapp));
  142. // After this point, nanoapp is null as we've transferred ownership into
  143. // mNanoapps.back() - use newNanoapp to reference it
  144. }
  145. mCurrentApp = newNanoapp;
  146. success = newNanoapp->start();
  147. mCurrentApp = nullptr;
  148. if (!success) {
  149. // TODO: to be fully safe, need to purge/flush any events and messages
  150. // sent by the nanoapp here (but don't call nanoappEnd). For now, we just
  151. // destroy the Nanoapp instance.
  152. LOGE("Nanoapp %" PRIu32 " failed to start", newNanoapp->getInstanceId());
  153. // Note that this lock protects against concurrent read and modification
  154. // of mNanoapps, but we are assured that no new nanoapps were added since
  155. // we pushed the new nanoapp
  156. LockGuard<Mutex> lock(mNanoappsLock);
  157. mNanoapps.pop_back();
  158. } else {
  159. notifyAppStatusChange(CHRE_EVENT_NANOAPP_STARTED, *newNanoapp);
  160. }
  161. }
  162. return success;
  163. }
  164. bool EventLoop::unloadNanoapp(uint32_t instanceId,
  165. bool allowSystemNanoappUnload) {
  166. bool unloaded = false;
  167. for (size_t i = 0; i < mNanoapps.size(); i++) {
  168. if (instanceId == mNanoapps[i]->getInstanceId()) {
  169. if (!allowSystemNanoappUnload && mNanoapps[i]->isSystemNanoapp()) {
  170. LOGE("Refusing to unload system nanoapp");
  171. } else {
  172. // Make sure all messages sent by this nanoapp at least have their
  173. // associated free callback processing pending in the event queue (i.e.
  174. // there are no messages pending delivery to the host)
  175. EventLoopManagerSingleton::get()->getHostCommsManager()
  176. .flushMessagesSentByNanoapp(mNanoapps[i]->getAppId());
  177. // Distribute all inbound events we have at this time - here we're
  178. // interested in handling any message free callbacks generated by
  179. // flushMessagesSentByNanoapp()
  180. flushInboundEventQueue();
  181. // Mark that this nanoapp is stopping early, so it can't send events or
  182. // messages during the nanoapp event queue flush
  183. mStoppingNanoapp = mNanoapps[i].get();
  184. // Process any pending events, with the intent of ensuring that we free
  185. // all events generated by this nanoapp
  186. flushNanoappEventQueues();
  187. // Post the unload event now (so we can reference the Nanoapp instance
  188. // directly), but nanoapps won't get it until after the unload completes
  189. notifyAppStatusChange(CHRE_EVENT_NANOAPP_STOPPED, *mStoppingNanoapp);
  190. // Finally, we are at a point where there should not be any pending
  191. // events or messages sent by the app that could potentially reference
  192. // the nanoapp's memory, so we are safe to unload it
  193. unloadNanoappAtIndex(i);
  194. mStoppingNanoapp = nullptr;
  195. // TODO: right now we assume that the nanoapp will clean up all of its
  196. // resource allocations in its nanoappEnd callback (memory, sensor
  197. // subscriptions, etc.), otherwise we're leaking resources. We should
  198. // perform resource cleanup automatically here to avoid these types of
  199. // potential leaks.
  200. LOGD("Unloaded nanoapp with instanceId %" PRIu32, instanceId);
  201. unloaded = true;
  202. }
  203. break;
  204. }
  205. }
  206. return unloaded;
  207. }
  208. bool EventLoop::postEventOrDie(uint16_t eventType, void *eventData,
  209. chreEventCompleteFunction *freeCallback,
  210. uint32_t targetInstanceId) {
  211. bool success = false;
  212. if (mRunning) {
  213. success = allocateAndPostEvent(eventType, eventData, freeCallback,
  214. kSystemInstanceId, targetInstanceId);
  215. if (!success) {
  216. // This can only happen if the event is a system event type. This
  217. // postEvent method will fail if a non-system event is posted when the
  218. // memory pool is close to full.
  219. FATAL_ERROR("Failed to allocate system event type %" PRIu16, eventType);
  220. }
  221. }
  222. return success;
  223. }
  224. bool EventLoop::postLowPriorityEventOrFree(
  225. uint16_t eventType, void *eventData,
  226. chreEventCompleteFunction *freeCallback, uint32_t senderInstanceId,
  227. uint32_t targetInstanceId) {
  228. bool success = false;
  229. if (mRunning) {
  230. if (mEventPool.getFreeBlockCount() > kMinReservedHighPriorityEventCount) {
  231. success = allocateAndPostEvent(eventType, eventData, freeCallback,
  232. senderInstanceId, targetInstanceId);
  233. }
  234. if (!success) {
  235. if (freeCallback != nullptr) {
  236. freeCallback(eventType, eventData);
  237. }
  238. LOGE("Failed to allocate event 0x%" PRIx16 " to instanceId %" PRIu32,
  239. eventType, targetInstanceId);
  240. }
  241. }
  242. return success;
  243. }
  244. void EventLoop::stop() {
  245. auto callback = [](uint16_t /* type */, void * /* data */) {
  246. EventLoopManagerSingleton::get()->getEventLoop().onStopComplete();
  247. };
  248. // Stop accepting new events and tell the main loop to finish.
  249. postEventOrDie(0, nullptr, callback, kSystemInstanceId);
  250. }
  251. void EventLoop::onStopComplete() {
  252. mRunning = false;
  253. }
  254. Nanoapp *EventLoop::findNanoappByInstanceId(uint32_t instanceId) const {
  255. ConditionalLockGuard<Mutex> lock(mNanoappsLock, !inEventLoopThread());
  256. return lookupAppByInstanceId(instanceId);
  257. }
  258. bool EventLoop::populateNanoappInfoForAppId(
  259. uint64_t appId, struct chreNanoappInfo *info) const {
  260. ConditionalLockGuard<Mutex> lock(mNanoappsLock, !inEventLoopThread());
  261. Nanoapp *app = lookupAppByAppId(appId);
  262. return populateNanoappInfo(app, info);
  263. }
  264. bool EventLoop::populateNanoappInfoForInstanceId(
  265. uint32_t instanceId, struct chreNanoappInfo *info) const {
  266. ConditionalLockGuard<Mutex> lock(mNanoappsLock, !inEventLoopThread());
  267. Nanoapp *app = lookupAppByInstanceId(instanceId);
  268. return populateNanoappInfo(app, info);
  269. }
  270. bool EventLoop::currentNanoappIsStopping() const {
  271. return (mCurrentApp == mStoppingNanoapp || !mRunning);
  272. }
  273. void EventLoop::logStateToBuffer(char *buffer, size_t *bufferPos,
  274. size_t bufferSize) const {
  275. debugDumpPrint(buffer, bufferPos, bufferSize, "\nNanoapps:\n");
  276. for (const UniquePtr<Nanoapp>& app : mNanoapps) {
  277. app->logStateToBuffer(buffer, bufferPos, bufferSize);
  278. }
  279. debugDumpPrint(buffer, bufferPos, bufferSize, "\nEvent Loop:\n");
  280. debugDumpPrint(buffer, bufferPos, bufferSize,
  281. " Max event pool usage: %zu/%zu\n",
  282. mMaxEventPoolUsage, kMaxEventCount);
  283. }
  284. bool EventLoop::allocateAndPostEvent(uint16_t eventType, void *eventData,
  285. chreEventCompleteFunction *freeCallback, uint32_t senderInstanceId,
  286. uint32_t targetInstanceId) {
  287. bool success = false;
  288. Milliseconds receivedTime = Nanoseconds(SystemTime::getMonotonicTime());
  289. // The event loop should never contain more than 65 seconds worth of data
  290. // unless something has gone terribly wrong so use uint16_t to save space.
  291. uint16_t receivedTimeMillis = receivedTime.getMilliseconds();
  292. Event *event = mEventPool.allocate(eventType, receivedTimeMillis, eventData,
  293. freeCallback, senderInstanceId,
  294. targetInstanceId);
  295. if (event != nullptr) {
  296. success = mEvents.push(event);
  297. }
  298. return success;
  299. }
  300. bool EventLoop::deliverEvents() {
  301. bool havePendingEvents = false;
  302. // Do one loop of round-robin. We might want to have some kind of priority or
  303. // time sharing in the future, but this should be good enough for now.
  304. for (const UniquePtr<Nanoapp>& app : mNanoapps) {
  305. if (app->hasPendingEvent()) {
  306. havePendingEvents |= deliverNextEvent(app);
  307. }
  308. }
  309. return havePendingEvents;
  310. }
  311. bool EventLoop::deliverNextEvent(const UniquePtr<Nanoapp>& app) {
  312. // TODO: cleaner way to set/clear this? RAII-style?
  313. mCurrentApp = app.get();
  314. Event *event = app->processNextEvent();
  315. mCurrentApp = nullptr;
  316. if (event->isUnreferenced()) {
  317. freeEvent(event);
  318. }
  319. return app->hasPendingEvent();
  320. }
  321. void EventLoop::distributeEvent(Event *event) {
  322. for (const UniquePtr<Nanoapp>& app : mNanoapps) {
  323. if ((event->targetInstanceId == chre::kBroadcastInstanceId
  324. && app->isRegisteredForBroadcastEvent(event->eventType))
  325. || event->targetInstanceId == app->getInstanceId()) {
  326. app->postEvent(event);
  327. }
  328. }
  329. if (event->isUnreferenced()) {
  330. // Events sent to the system instance ID are processed via the free callback
  331. // and are not expected to be delivered to any nanoapp, so no need to log a
  332. // warning in that case
  333. if (event->senderInstanceId != kSystemInstanceId) {
  334. LOGW("Dropping event 0x%" PRIx16, event->eventType);
  335. }
  336. freeEvent(event);
  337. }
  338. }
  339. void EventLoop::flushInboundEventQueue() {
  340. while (!mEvents.empty()) {
  341. distributeEvent(mEvents.pop());
  342. }
  343. }
  344. void EventLoop::flushNanoappEventQueues() {
  345. while (deliverEvents());
  346. }
  347. void EventLoop::freeEvent(Event *event) {
  348. if (event->freeCallback != nullptr) {
  349. // TODO: find a better way to set the context to the creator of the event
  350. mCurrentApp = lookupAppByInstanceId(event->senderInstanceId);
  351. event->freeCallback(event->eventType, event->eventData);
  352. mCurrentApp = nullptr;
  353. }
  354. mEventPool.deallocate(event);
  355. }
  356. Nanoapp *EventLoop::lookupAppByAppId(uint64_t appId) const {
  357. for (const UniquePtr<Nanoapp>& app : mNanoapps) {
  358. if (app->getAppId() == appId) {
  359. return app.get();
  360. }
  361. }
  362. return nullptr;
  363. }
  364. Nanoapp *EventLoop::lookupAppByInstanceId(uint32_t instanceId) const {
  365. // The system instance ID always has nullptr as its Nanoapp pointer, so can
  366. // skip iterating through the nanoapp list for that case
  367. if (instanceId != kSystemInstanceId) {
  368. for (const UniquePtr<Nanoapp>& app : mNanoapps) {
  369. if (app->getInstanceId() == instanceId) {
  370. return app.get();
  371. }
  372. }
  373. }
  374. return nullptr;
  375. }
  376. void EventLoop::notifyAppStatusChange(uint16_t eventType,
  377. const Nanoapp& nanoapp) {
  378. auto *info = memoryAlloc<chreNanoappInfo>();
  379. if (info == nullptr) {
  380. LOG_OOM();
  381. } else {
  382. info->appId = nanoapp.getAppId();
  383. info->version = nanoapp.getAppVersion();
  384. info->instanceId = nanoapp.getInstanceId();
  385. postEventOrDie(eventType, info, freeEventDataCallback);
  386. }
  387. }
  388. void EventLoop::unloadNanoappAtIndex(size_t index) {
  389. const UniquePtr<Nanoapp>& nanoapp = mNanoapps[index];
  390. // Lock here to prevent the nanoapp instance from being accessed between the
  391. // time it is ended and fully erased
  392. LockGuard<Mutex> lock(mNanoappsLock);
  393. // Let the app know it's going away
  394. mCurrentApp = nanoapp.get();
  395. nanoapp->end();
  396. mCurrentApp = nullptr;
  397. // Destroy the Nanoapp instance
  398. mNanoapps.erase(index);
  399. }
  400. } // namespace chre