event_loop.h revision 341292509cfde0f859d89bda4ca5d55fc9772e64
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   * Starts a nanoapp by constructing a Nanoapp instance, invoking the start
77   * entry point and adding it to the list of nanoapps owned by this event
78   * loop.
79   *
80   * @param platformNanoapp A pointer to the platform nanoapp to start. This
81   *        pointer must remain valid after this function returns.
82   * @return True if the app was started successfully.
83   */
84  bool startNanoapp(PlatformNanoapp *platformNanoapp);
85
86  /**
87   * Stops a nanoapp by invoking the stop entry point. The nanoapp passed in
88   * must have been previously started by the startNanoapp method.
89   *
90   * @param A pointer to the nanoapp to stop.
91   */
92  void stopNanoapp(Nanoapp *nanoapp);
93
94  /**
95   * Executes the loop that blocks on the event queue and delivers received
96   * events to nanoapps. Only returns after stop() is called (from another
97   * context).
98   */
99  void run();
100
101  /**
102   * Signals the event loop currently executing in run() to exit gracefully at
103   * the next available opportunity. This function is thread-safe.
104   */
105  void stop();
106
107  /**
108   * Posts an event to a nanoapp that is currently running (or all nanoapps if
109   * the target instance ID is kBroadcastInstanceId).
110   *
111   * This function is safe to call from any thread.
112   *
113   * @param The type of data being posted.
114   * @param The data being posted.
115   * @param The callback to invoke when the event is no longer needed.
116   * @param The instance ID of the sender of this event.
117   * @param The instance ID of the destination of this event.
118   *
119   * @return true if the event was successfully added to the queue
120   */
121  bool postEvent(uint16_t eventType, void *eventData,
122                 chreEventCompleteFunction *freeCallback,
123                 uint32_t senderInstanceId = kSystemInstanceId,
124                 uint32_t targetInstanceId = kBroadcastInstanceId);
125
126  /**
127   * Returns a pointer to the currently executing Nanoapp, or nullptr if none is
128   * currently executing. Must only be called from within the thread context
129   * associated with this EventLoop.
130   *
131   * @return the currently executing nanoapp, or nullptr
132   */
133  Nanoapp *getCurrentNanoapp() const;
134
135  /**
136   * Gets the number of nanoapps currently associated with this event loop. Must
137   * only be called within the context of this EventLoop.
138   *
139   * @return The number of nanoapps managed by this event loop
140   */
141  size_t getNanoappCount() const;
142
143  /**
144   * Obtains the TimerPool associated with this event loop.
145   *
146   * @return The timer pool owned by this event loop.
147   */
148  TimerPool& getTimerPool();
149
150  /**
151   * Searches the set of nanoapps managed by this EventLoop for one with the
152   * given instance ID.
153   *
154   * This function is safe to call from any thread.
155   *
156   * @param instanceId The nanoapp instance ID to search for.
157   * @return a pointer to the found nanoapp or nullptr if no match was found.
158   */
159  Nanoapp *findNanoappByInstanceId(uint32_t instanceId);
160
161 private:
162  //! The maximum number of events that can be active in the system.
163  static constexpr size_t kMaxEventCount = 1024;
164
165  //! The maximum number of events that are awaiting to be scheduled. These
166  //! events are in a queue to be distributed to apps.
167  static constexpr size_t kMaxUnscheduledEventCount = 1024;
168
169  //! The memory pool to allocate incoming events from.
170  SynchronizedMemoryPool<Event, kMaxEventCount> mEventPool;
171
172  //! The timer used schedule timed events for tasks running in this event loop.
173  TimerPool mTimerPool;
174
175  //! The list of nanoapps managed by this event loop.
176  DynamicVector<UniquePtr<Nanoapp>> mNanoapps;
177
178  //! This lock *must* be held whenever we:
179  //!   (1) make changes to the mNanoapps vector, or
180  //!   (2) read the mNanoapps vector from a thread other than the one
181  //!       associated with this EventLoop
182  //! It is not necessary to acquire the lock when reading mNanoapps from within
183  //! the thread context of this EventLoop.
184  Mutex mNanoappsLock;
185
186  //! The blocking queue of incoming events from the system that have not been
187  //!  distributed out to apps yet.
188  FixedSizeBlockingQueue<Event *, kMaxUnscheduledEventCount> mEvents;
189
190  // TODO: should probably be atomic to be fully correct
191  volatile bool mRunning = false;
192
193  Nanoapp *mCurrentApp = nullptr;
194
195  /**
196   * Call after when an Event has been delivered to all intended recipients.
197   * Invokes the event's free callback (if given) and releases resources.
198   *
199   * @param event The event to be freed
200   */
201  void freeEvent(Event *event);
202
203  /**
204   * Finds a Nanoapp with the given instanceId.
205   *
206   * Only safe to call within this EventLoop's thread.
207   *
208   * @param instanceId Nanoapp instance identifier
209   * @return Nanoapp with the given instanceId, or nullptr if not found
210   */
211  Nanoapp *lookupAppByInstanceId(uint32_t instanceId);
212};
213
214}  // namespace chre
215
216#endif  // CHRE_CORE_EVENT_LOOP_H_
217