event_loop.h revision 9d5b500a223ef73560f0dce38f50b809bde5dd0d
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/util/dynamic_vector.h"
26#include "chre/util/fixed_size_blocking_queue.h"
27#include "chre/util/non_copyable.h"
28#include "chre/util/synchronized_memory_pool.h"
29#include "chre/util/unique_ptr.h"
30
31namespace chre {
32
33/**
34 * The EventLoop represents a single thread of execution that is shared among
35 * zero or more nanoapps. As the name implies, the EventLoop is built around a
36 * loop that delivers events to the nanoapps managed within for processing.
37 */
38class EventLoop : public NonCopyable {
39 public:
40  /**
41   * Setup the event loop.
42   */
43  EventLoop();
44
45  /**
46   * Synchronous callback used with forEachNanoapp
47   */
48  typedef void (NanoappCallbackFunction)(const Nanoapp *nanoapp, void *data);
49
50  /**
51   * Searches the set of nanoapps managed by this EventLoop for one with the
52   * given app ID. If found, provides its instance ID, which can be used to send
53   * events to the app.
54   *
55   * This function is safe to call from any thread.
56   *
57   * @param appId The nanoapp identifier to search for.
58   * @param instanceId If this function returns true, will be populated with the
59   *        instanceId associated with the given appId; otherwise unmodified.
60   *        Must not be null.
61   * @return true if the given app ID was found and instanceId was populated
62   */
63  bool findNanoappInstanceIdByAppId(uint64_t appId, uint32_t *instanceId);
64
65  /**
66   * Iterates over the list of Nanoapps managed by this EventLoop, and invokes
67   * the supplied callback for each one. This holds a lock if necessary, so it
68   * is safe to call from any thread.
69   *
70   * @param callback Function to invoke on each Nanoapp (synchronously)
71   * @param data Arbitrary data to pass to the callback
72   */
73  void forEachNanoapp(NanoappCallbackFunction *callback, void *data);
74
75  /**
76   * Invokes the Nanoapp's start callback, and if successful, adds it to the
77   * set of Nanoapps managed by this EventLoop. This function must only be
78   * called from the context of the thread that runs this event loop (i.e. from
79   * the same thread that will call run() or from a callback invoked within
80   * run()).
81   *
82   * @param nanoapp The nanoapp that will be started. Upon success, this
83   *        UniquePtr will become invalid, as the underlying Nanoapp instance
84   *        will have been transferred to be managed by this EventLoop.
85   * @return true if the app was started successfully
86   */
87  bool startNanoapp(UniquePtr<Nanoapp>& nanoapp);
88
89  /**
90   * Stops a nanoapp by invoking the stop entry point. The nanoapp passed in
91   * must have been previously started by the startNanoapp method.
92   *
93   * @param A pointer to the nanoapp to stop.
94   */
95  void stopNanoapp(Nanoapp *nanoapp);
96
97  /**
98   * Executes the loop that blocks on the event queue and delivers received
99   * events to nanoapps. Only returns after stop() is called (from another
100   * context).
101   */
102  void run();
103
104  /**
105   * Signals the event loop currently executing in run() to exit gracefully at
106   * the next available opportunity. This function is thread-safe.
107   */
108  void stop();
109
110  /**
111   * Posts an event to a nanoapp that is currently running (or all nanoapps if
112   * the target instance ID is kBroadcastInstanceId).
113   *
114   * This function is safe to call from any thread.
115   *
116   * @param The type of data being posted.
117   * @param The data being posted.
118   * @param The callback to invoke when the event is no longer needed.
119   * @param The instance ID of the sender of this event.
120   * @param The instance ID of the destination of this event.
121   *
122   * @return true if the event was successfully added to the queue
123   */
124  bool postEvent(uint16_t eventType, void *eventData,
125                 chreEventCompleteFunction *freeCallback,
126                 uint32_t senderInstanceId = kSystemInstanceId,
127                 uint32_t targetInstanceId = kBroadcastInstanceId);
128
129  /**
130   * Returns a pointer to the currently executing Nanoapp, or nullptr if none is
131   * currently executing. Must only be called from within the thread context
132   * associated with this EventLoop.
133   *
134   * @return the currently executing nanoapp, or nullptr
135   */
136  Nanoapp *getCurrentNanoapp() const;
137
138  /**
139   * Gets the number of nanoapps currently associated with this event loop. Must
140   * only be called within the context of this EventLoop.
141   *
142   * @return The number of nanoapps managed by this event loop
143   */
144  size_t getNanoappCount() const;
145
146  /**
147   * Obtains the TimerPool associated with this event loop.
148   *
149   * @return The timer pool owned by this event loop.
150   */
151  TimerPool& getTimerPool();
152
153  /**
154   * Searches the set of nanoapps managed by this EventLoop for one with the
155   * given instance ID.
156   *
157   * This function is safe to call from any thread.
158   *
159   * @param instanceId The nanoapp instance ID to search for.
160   * @return a pointer to the found nanoapp or nullptr if no match was found.
161   */
162  Nanoapp *findNanoappByInstanceId(uint32_t instanceId);
163
164 private:
165  //! The maximum number of events that can be active in the system.
166  static constexpr size_t kMaxEventCount = 1024;
167
168  //! The maximum number of events that are awaiting to be scheduled. These
169  //! events are in a queue to be distributed to apps.
170  static constexpr size_t kMaxUnscheduledEventCount = 1024;
171
172  //! The memory pool to allocate incoming events from.
173  SynchronizedMemoryPool<Event, kMaxEventCount> mEventPool;
174
175  //! The timer used schedule timed events for tasks running in this event loop.
176  TimerPool mTimerPool;
177
178  //! The list of nanoapps managed by this event loop.
179  DynamicVector<UniquePtr<Nanoapp>> mNanoapps;
180
181  //! This lock *must* be held whenever we:
182  //!   (1) make changes to the mNanoapps vector, or
183  //!   (2) read the mNanoapps vector from a thread other than the one
184  //!       associated with this EventLoop
185  //! It is not necessary to acquire the lock when reading mNanoapps from within
186  //! the thread context of this EventLoop.
187  Mutex mNanoappsLock;
188
189  //! The blocking queue of incoming events from the system that have not been
190  //!  distributed out to apps yet.
191  FixedSizeBlockingQueue<Event *, kMaxUnscheduledEventCount> mEvents;
192
193  // TODO: should probably be atomic to be fully correct
194  volatile bool mRunning = false;
195
196  Nanoapp *mCurrentApp = nullptr;
197
198  /**
199   * Call after when an Event has been delivered to all intended recipients.
200   * Invokes the event's free callback (if given) and releases resources.
201   *
202   * @param event The event to be freed
203   */
204  void freeEvent(Event *event);
205
206  /**
207   * Finds a Nanoapp with the given instanceId.
208   *
209   * Only safe to call within this EventLoop's thread.
210   *
211   * @param instanceId Nanoapp instance identifier
212   * @return Nanoapp with the given instanceId, or nullptr if not found
213   */
214  Nanoapp *lookupAppByInstanceId(uint32_t instanceId);
215};
216
217}  // namespace chre
218
219#endif  // CHRE_CORE_EVENT_LOOP_H_
220