event_loop.h revision 4e21bdadf6ed0242146cdd22f79e53a1979ed2ed
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#ifndef CHRE_CORE_EVENT_LOOP_H_
18#define CHRE_CORE_EVENT_LOOP_H_
19
20#include "chre/core/event.h"
21#include "chre/core/nanoapp.h"
22#include "chre/core/timer_pool.h"
23#include "chre/platform/mutex.h"
24#include "chre/platform/platform_nanoapp.h"
25#include "chre/platform/power_control_manager.h"
26#include "chre/util/dynamic_vector.h"
27#include "chre/util/fixed_size_blocking_queue.h"
28#include "chre/util/non_copyable.h"
29#include "chre/util/synchronized_memory_pool.h"
30#include "chre/util/unique_ptr.h"
31#include "chre_api/chre/event.h"
32
33namespace chre {
34
35/**
36 * The EventLoop represents a single thread of execution that is shared among
37 * zero or more nanoapps. As the name implies, the EventLoop is built around a
38 * loop that delivers events to the nanoapps managed within for processing.
39 */
40class EventLoop : public NonCopyable {
41 public:
42  /**
43   * Synchronous callback used with forEachNanoapp
44   */
45  typedef void (NanoappCallbackFunction)(const Nanoapp *nanoapp, void *data);
46
47  /**
48   * Searches the set of nanoapps managed by this EventLoop for one with the
49   * given app ID. If found, provides its instance ID, which can be used to send
50   * events to the app.
51   *
52   * This function is safe to call from any thread.
53   *
54   * @param appId The nanoapp identifier to search for.
55   * @param instanceId If this function returns true, will be populated with the
56   *        instanceId associated with the given appId; otherwise unmodified.
57   *        Must not be null.
58   * @return true if the given app ID was found and instanceId was populated
59   */
60  bool findNanoappInstanceIdByAppId(uint64_t appId, uint32_t *instanceId) const;
61
62  /**
63   * Iterates over the list of Nanoapps managed by this EventLoop, and invokes
64   * the supplied callback for each one. This holds a lock if necessary, so it
65   * is safe to call from any thread.
66   *
67   * @param callback Function to invoke on each Nanoapp (synchronously)
68   * @param data Arbitrary data to pass to the callback
69   */
70  void forEachNanoapp(NanoappCallbackFunction *callback, void *data);
71
72  /**
73   * Invokes a message to host free callback supplied by the given nanoapp
74   * (identified by app ID). Ensures that the calling context is updated
75   * appropriately.
76   *
77   * @param appId Identifies the nanoapp that sent this message and supplied the
78   *        free callback
79   * @param freeFunction The non-null message free callback given by the nanoapp
80   * @param message Pointer to the message data
81   * @param messageSize Size of the message
82   */
83  void invokeMessageFreeFunction(
84      uint64_t appId, chreMessageFreeFunction *freeFunction, void *message,
85      size_t messageSize);
86
87  /**
88   * Invokes the Nanoapp's start callback, and if successful, adds it to the
89   * set of Nanoapps managed by this EventLoop. This function must only be
90   * called from the context of the thread that runs this event loop (i.e. from
91   * the same thread that will call run() or from a callback invoked within
92   * run()).
93   *
94   * @param nanoapp The nanoapp that will be started. Upon success, this
95   *        UniquePtr will become invalid, as the underlying Nanoapp instance
96   *        will have been transferred to be managed by this EventLoop.
97   * @return true if the app was started successfully
98   */
99  bool startNanoapp(UniquePtr<Nanoapp>& nanoapp);
100
101  /**
102   * Stops and unloads a nanoapp identified by its instance ID. The end entry
103   * point will be invoked, and the chre::Nanoapp instance will be destroyed.
104   * After this function returns, all references to the Nanoapp instance are
105   * invalidated.
106   *
107   * @param instanceId The nanoapp's unique instance identifier
108   * @param allowSystemNanoappUnload If false, this function will reject
109   *        attempts to unload a system nanoapp
110   *
111   * @return true if the nanoapp with the given instance ID was found & unloaded
112   */
113  bool unloadNanoapp(uint32_t instanceId, bool allowSystemNanoappUnload);
114
115  /**
116   * Executes the loop that blocks on the event queue and delivers received
117   * events to nanoapps. Only returns after stop() is called (from another
118   * context).
119   */
120  void run();
121
122  /**
123   * Signals the event loop currently executing in run() to exit gracefully at
124   * the next available opportunity. This function is thread-safe.
125   */
126  void stop();
127
128  /**
129   * Posts an event to a nanoapp that is currently running (or all nanoapps if
130   * the target instance ID is kBroadcastInstanceId).
131   *
132   * This function is safe to call from any thread.
133   *
134   * @param eventType The type of data being posted.
135   * @param eventData The data being posted.
136   * @param freeCallback The callback to invoke when the event is no longer
137   *        needed.
138   * @param senderInstanceId The instance ID of the sender of this event.
139   * @param targetInstanceId The instance ID of the destination of this event.
140   *
141   * @return true if the event was successfully added to the queue. Note that
142   *         unlike chreSendEvent, this does *not* invoke the free callback if
143   *         it failed to post the event.
144   *
145   * @see chreSendEvent
146   */
147  bool postEvent(uint16_t eventType, void *eventData,
148                 chreEventCompleteFunction *freeCallback,
149                 uint32_t senderInstanceId = kSystemInstanceId,
150                 uint32_t targetInstanceId = kBroadcastInstanceId);
151
152  /**
153   * Returns a pointer to the currently executing Nanoapp, or nullptr if none is
154   * currently executing. Must only be called from within the thread context
155   * associated with this EventLoop.
156   *
157   * @return the currently executing nanoapp, or nullptr
158   */
159  Nanoapp *getCurrentNanoapp() const {
160    return mCurrentApp;
161  }
162
163  /**
164   * Gets the number of nanoapps currently associated with this event loop. Must
165   * only be called within the context of this EventLoop.
166   *
167   * @return The number of nanoapps managed by this event loop
168   */
169  size_t getNanoappCount() const {
170    return mNanoapps.size();
171  }
172
173  /**
174   * Obtains the TimerPool associated with this event loop.
175   *
176   * @return The timer pool owned by this event loop.
177   */
178  TimerPool& getTimerPool() {
179    return mTimerPool;
180  }
181
182  /**
183   * Searches the set of nanoapps managed by this EventLoop for one with the
184   * given instance ID.
185   *
186   * This function is safe to call from any thread.
187   *
188   * @param instanceId The nanoapp instance ID to search for.
189   * @return a pointer to the found nanoapp or nullptr if no match was found.
190   */
191  Nanoapp *findNanoappByInstanceId(uint32_t instanceId) const;
192
193  /**
194   * Looks for an app with the given ID and if found, populates info with its
195   * metadata. Safe to call from any thread.
196   *
197   * @see chreGetNanoappInfoByAppId
198   */
199  bool populateNanoappInfoForAppId(uint64_t appId,
200                                   struct chreNanoappInfo *info) const;
201
202  /**
203   * Looks for an app with the given instance ID and if found, populates info
204   * with its metadata. Safe to call from any thread.
205   *
206   * @see chreGetNanoappInfoByInstanceId
207   */
208  bool populateNanoappInfoForInstanceId(uint32_t instanceId,
209                                        struct chreNanoappInfo *info) const;
210
211  /**
212   * @return true if the current Nanoapp (or entire CHRE) is being unloaded, and
213   *         therefore it should not be allowed to send events or messages, etc.
214   */
215  bool currentNanoappIsStopping() const;
216
217  /**
218   * Prints state in a string buffer. Must only be called from the context of
219   * the main CHRE thread.
220   *
221   * @param buffer Pointer to the start of the buffer.
222   * @param bufferPos Pointer to buffer position to start the print (in-out).
223   * @param size Size of the buffer in bytes.
224   *
225   * @return true if entire log printed, false if overflow or error.
226   */
227  bool logStateToBuffer(char *buffer, size_t *bufferPos,
228                        size_t bufferSize) const;
229
230
231  /**
232   * Returns a reference to the power control manager. This allows power
233   * controls from subsystems outside the event loops.
234   */
235  PowerControlManager& getPowerControlManager() {
236    return mPowerControlManager;
237  }
238
239 private:
240  //! The maximum number of events that can be active in the system.
241  static constexpr size_t kMaxEventCount = 256;
242
243  //! The maximum number of events that are awaiting to be scheduled. These
244  //! events are in a queue to be distributed to apps.
245  static constexpr size_t kMaxUnscheduledEventCount = 256;
246
247  //! The memory pool to allocate incoming events from.
248  SynchronizedMemoryPool<Event, kMaxEventCount> mEventPool;
249
250  //! The timer used schedule timed events for tasks running in this event loop.
251  TimerPool mTimerPool;
252
253  //! The list of nanoapps managed by this event loop.
254  DynamicVector<UniquePtr<Nanoapp>> mNanoapps;
255
256  //! This lock *must* be held whenever we:
257  //!   (1) make changes to the mNanoapps vector, or
258  //!   (2) read the mNanoapps vector from a thread other than the one
259  //!       associated with this EventLoop
260  //! It is not necessary to acquire the lock when reading mNanoapps from within
261  //! the thread context of this EventLoop.
262  mutable Mutex mNanoappsLock;
263
264  //! The blocking queue of incoming events from the system that have not been
265  //! distributed out to apps yet.
266  FixedSizeBlockingQueue<Event *, kMaxUnscheduledEventCount> mEvents;
267
268  // TODO: should probably be atomic to be fully correct
269  volatile bool mRunning = true;
270
271  //! The nanoapp that is currently executing - must be set any time we call
272  //! into the nanoapp's entry points or callbacks
273  Nanoapp *mCurrentApp = nullptr;
274
275  //! Set to the nanoapp we are in the process of unloading in unloadNanoapp()
276  Nanoapp *mStoppingNanoapp = nullptr;
277
278  //! The object which manages power related controls.
279  PowerControlManager mPowerControlManager;
280
281  /**
282   * Do one round of Nanoapp event delivery, only considering events in
283   * Nanoapps' own queues (not mEvents).
284   *
285   * @return true if there are more events pending in Nanoapps' own queues
286   */
287  bool deliverEvents();
288
289  /**
290   * Delivers the next event pending in the Nanoapp's queue, and takes care of
291   * freeing events once they have been delivered to all nanoapps. Must only be
292   * called after confirming that the app has at least 1 pending event.
293   *
294   * @return true if the nanoapp has another event pending in its queue
295   */
296  bool deliverNextEvent(const UniquePtr<Nanoapp>& app);
297
298  /**
299   * Given an event pulled from the main incoming event queue (mEvents), deliver
300   * it to all Nanoapps that should receive the event, or free the event if
301   * there are no valid recipients.
302   *
303   * @param event The Event to distribute to Nanoapps
304   */
305  void distributeEvent(Event *event);
306
307  /**
308   * Distribute all events pending in the inbound event queue. Note that this
309   * function only guarantees that any events in the inbound queue at the time
310   * it is called will be distributed to Nanoapp event queues - new events may
311   * still be posted during or after this function call from other threads as
312   * long as postEvent() will accept them.
313   */
314  void flushInboundEventQueue();
315
316  /**
317   * Delivers events pending in Nanoapps' own queues until they are all empty.
318   */
319  void flushNanoappEventQueues();
320
321  /**
322   * Call after when an Event has been delivered to all intended recipients.
323   * Invokes the event's free callback (if given) and releases resources.
324   *
325   * @param event The event to be freed
326   */
327  void freeEvent(Event *event);
328
329  /**
330   * Finds a Nanoapp with the given 64-bit appId.
331   *
332   * Only safe to call within this EventLoop's thread, or if mNanoappsLock is
333   * held.
334   *
335   * @param appId Nanoapp ID
336   * @return Pointer to Nanoapp instance in this EventLoop with the given app
337   *         ID, or nullptr if not found
338   */
339  Nanoapp *lookupAppByAppId(uint64_t appId) const;
340
341  /**
342   * Finds a Nanoapp with the given instanceId.
343   *
344   * Only safe to call within this EventLoop's thread, or if mNanoappsLock is
345   * held.
346   *
347   * @param instanceId Nanoapp instance identifier
348   * @return Nanoapp with the given instanceId, or nullptr if not found
349   */
350  Nanoapp *lookupAppByInstanceId(uint32_t instanceId) const;
351
352  /**
353   * Sends an event with payload struct chreNanoappInfo populated from the given
354   * Nanoapp instance to inform other nanoapps about it starting/stopping.
355   *
356   * @param eventType Should be one of CHRE_EVENT_NANOAPP_{STARTED, STOPPED}
357   * @param nanoapp The nanoapp instance whose status has changed
358   */
359  void notifyAppStatusChange(uint16_t eventType, const Nanoapp& nanoapp);
360
361  /**
362   * Stops and unloads the Nanoapp at the given index in mNanoapps.
363   *
364   * IMPORTANT: prior to calling this function, the event queues must be in a
365   * safe condition for removal of this nanoapp. This means that there must not
366   * be any pending events in this nanoapp's queue, and there must not be any
367   * outstanding events sent by this nanoapp, as they may reference the
368   * nanoapp's own memory (even if there is no free callback).
369   */
370  void unloadNanoappAtIndex(size_t index);
371};
372
373}  // namespace chre
374
375#endif  // CHRE_CORE_EVENT_LOOP_H_
376