blob: 15c989176b6521cba20b5cc810dfcccf42a42625 [file] [log] [blame]
Jeff Brown7901eb22010-09-13 23:17:30 -07001/*
2 * Copyright (C) 2010 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 UTILS_LOOPER_H
18#define UTILS_LOOPER_H
19
20#include <utils/threads.h>
21#include <utils/RefBase.h>
22#include <utils/KeyedVector.h>
Jeff Brown8d15c742010-10-05 15:35:37 -070023#include <utils/Timers.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070024
Jeff Brown8d15c742010-10-05 15:35:37 -070025#include <sys/epoll.h>
Jeff Brown8d15c742010-10-05 15:35:37 -070026
Jeff Brown7901eb22010-09-13 23:17:30 -070027namespace android {
28
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080029/*
30 * NOTE: Since Looper is used to implement the NDK ALooper, the Looper
31 * enums and the signature of Looper_callbackFunc need to align with
32 * that implementation.
33 */
34
35/**
36 * For callback-based event loops, this is the prototype of the function
37 * that is called when a file descriptor event occurs.
38 * It is given the file descriptor it is associated with,
39 * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
40 * and the data pointer that was originally supplied.
41 *
42 * Implementations should return 1 to continue receiving callbacks, or 0
43 * to have this file descriptor and callback unregistered from the looper.
44 */
45typedef int (*Looper_callbackFunc)(int fd, int events, void* data);
46
Jeff Brown7901eb22010-09-13 23:17:30 -070047/**
Jeff Brown3e2e38b2011-03-02 14:41:58 -080048 * A message that can be posted to a Looper.
49 */
50struct Message {
51 Message() : what(0) { }
52 Message(int what) : what(what) { }
53
54 /* The message type. (interpretation is left up to the handler) */
55 int what;
56};
57
58
59/**
60 * Interface for a Looper message handler.
61 *
62 * The Looper holds a strong reference to the message handler whenever it has
63 * a message to deliver to it. Make sure to call Looper::removeMessages
64 * to remove any pending messages destined for the handler so that the handler
65 * can be destroyed.
66 */
67class MessageHandler : public virtual RefBase {
68protected:
69 virtual ~MessageHandler() { }
70
71public:
72 /**
73 * Handles a message.
74 */
75 virtual void handleMessage(const Message& message) = 0;
76};
77
78
79/**
80 * A simple proxy that holds a weak reference to a message handler.
81 */
82class WeakMessageHandler : public MessageHandler {
Jeff Browndd1b0372012-05-31 16:15:35 -070083protected:
84 virtual ~WeakMessageHandler();
85
Jeff Brown3e2e38b2011-03-02 14:41:58 -080086public:
87 WeakMessageHandler(const wp<MessageHandler>& handler);
88 virtual void handleMessage(const Message& message);
89
90private:
91 wp<MessageHandler> mHandler;
92};
93
94
95/**
Jeff Browndd1b0372012-05-31 16:15:35 -070096 * A looper callback.
97 */
98class LooperCallback : public virtual RefBase {
99protected:
100 virtual ~LooperCallback() { }
101
102public:
103 /**
104 * Handles a poll event for the given file descriptor.
105 * It is given the file descriptor it is associated with,
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800106 * a bitmask of the poll events that were triggered (typically EVENT_INPUT),
Jeff Browndd1b0372012-05-31 16:15:35 -0700107 * and the data pointer that was originally supplied.
108 *
109 * Implementations should return 1 to continue receiving callbacks, or 0
110 * to have this file descriptor and callback unregistered from the looper.
111 */
112 virtual int handleEvent(int fd, int events, void* data) = 0;
113};
114
Jeff Browndd1b0372012-05-31 16:15:35 -0700115/**
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800116 * Wraps a Looper_callbackFunc function pointer.
Jeff Browndd1b0372012-05-31 16:15:35 -0700117 */
118class SimpleLooperCallback : public LooperCallback {
119protected:
120 virtual ~SimpleLooperCallback();
121
122public:
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800123 SimpleLooperCallback(Looper_callbackFunc callback);
Jeff Browndd1b0372012-05-31 16:15:35 -0700124 virtual int handleEvent(int fd, int events, void* data);
125
126private:
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800127 Looper_callbackFunc mCallback;
Jeff Browndd1b0372012-05-31 16:15:35 -0700128};
129
Jeff Browndd1b0372012-05-31 16:15:35 -0700130/**
Jeff Brown7901eb22010-09-13 23:17:30 -0700131 * A polling loop that supports monitoring file descriptor events, optionally
132 * using callbacks. The implementation uses epoll() internally.
133 *
134 * A looper can be associated with a thread although there is no requirement that it must be.
135 */
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800136class Looper : public RefBase {
Jeff Brown7901eb22010-09-13 23:17:30 -0700137protected:
138 virtual ~Looper();
139
140public:
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800141 enum {
142 /**
143 * Result from Looper_pollOnce() and Looper_pollAll():
144 * The poll was awoken using wake() before the timeout expired
145 * and no callbacks were executed and no other file descriptors were ready.
146 */
147 POLL_WAKE = -1,
148
149 /**
150 * Result from Looper_pollOnce() and Looper_pollAll():
151 * One or more callbacks were executed.
152 */
153 POLL_CALLBACK = -2,
154
155 /**
156 * Result from Looper_pollOnce() and Looper_pollAll():
157 * The timeout expired.
158 */
159 POLL_TIMEOUT = -3,
160
161 /**
162 * Result from Looper_pollOnce() and Looper_pollAll():
163 * An error occurred.
164 */
165 POLL_ERROR = -4,
166 };
167
168 /**
169 * Flags for file descriptor events that a looper can monitor.
170 *
171 * These flag bits can be combined to monitor multiple events at once.
172 */
173 enum {
174 /**
175 * The file descriptor is available for read operations.
176 */
177 EVENT_INPUT = 1 << 0,
178
179 /**
180 * The file descriptor is available for write operations.
181 */
182 EVENT_OUTPUT = 1 << 1,
183
184 /**
185 * The file descriptor has encountered an error condition.
186 *
187 * The looper always sends notifications about errors; it is not necessary
188 * to specify this event flag in the requested event set.
189 */
190 EVENT_ERROR = 1 << 2,
191
192 /**
193 * The file descriptor was hung up.
194 * For example, indicates that the remote end of a pipe or socket was closed.
195 *
196 * The looper always sends notifications about hangups; it is not necessary
197 * to specify this event flag in the requested event set.
198 */
199 EVENT_HANGUP = 1 << 3,
200
201 /**
202 * The file descriptor is invalid.
203 * For example, the file descriptor was closed prematurely.
204 *
205 * The looper always sends notifications about invalid file descriptors; it is not necessary
206 * to specify this event flag in the requested event set.
207 */
208 EVENT_INVALID = 1 << 4,
209 };
210
211 enum {
212 /**
213 * Option for Looper_prepare: this looper will accept calls to
214 * Looper_addFd() that do not have a callback (that is provide NULL
215 * for the callback). In this case the caller of Looper_pollOnce()
216 * or Looper_pollAll() MUST check the return from these functions to
217 * discover when data is available on such fds and process it.
218 */
219 PREPARE_ALLOW_NON_CALLBACKS = 1<<0
220 };
221
Jeff Brown7901eb22010-09-13 23:17:30 -0700222 /**
223 * Creates a looper.
224 *
225 * If allowNonCallbaks is true, the looper will allow file descriptors to be
226 * registered without associated callbacks. This assumes that the caller of
227 * pollOnce() is prepared to handle callback-less events itself.
228 */
229 Looper(bool allowNonCallbacks);
230
231 /**
232 * Returns whether this looper instance allows the registration of file descriptors
233 * using identifiers instead of callbacks.
234 */
235 bool getAllowNonCallbacks() const;
236
237 /**
238 * Waits for events to be available, with optional timeout in milliseconds.
239 * Invokes callbacks for all file descriptors on which an event occurred.
240 *
241 * If the timeout is zero, returns immediately without blocking.
242 * If the timeout is negative, waits indefinitely until an event appears.
243 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800244 * Returns POLL_WAKE if the poll was awoken using wake() before
Jeff Brown7901eb22010-09-13 23:17:30 -0700245 * the timeout expired and no callbacks were invoked and no other file
246 * descriptors were ready.
247 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800248 * Returns POLL_CALLBACK if one or more callbacks were invoked.
Jeff Brown7901eb22010-09-13 23:17:30 -0700249 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800250 * Returns POLL_TIMEOUT if there was no data before the given
Jeff Brown7901eb22010-09-13 23:17:30 -0700251 * timeout expired.
252 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800253 * Returns POLL_ERROR if an error occurred.
Jeff Brown7901eb22010-09-13 23:17:30 -0700254 *
255 * Returns a value >= 0 containing an identifier if its file descriptor has data
256 * and it has no callback function (requiring the caller here to handle it).
257 * In this (and only this) case outFd, outEvents and outData will contain the poll
258 * events and data associated with the fd, otherwise they will be set to NULL.
259 *
260 * This method does not return until it has finished invoking the appropriate callbacks
261 * for all file descriptors that were signalled.
262 */
Jeff Brown905682a2010-09-16 18:28:12 -0700263 int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
264 inline int pollOnce(int timeoutMillis) {
265 return pollOnce(timeoutMillis, NULL, NULL, NULL);
266 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700267
268 /**
269 * Like pollOnce(), but performs all pending callbacks until all
270 * data has been consumed or a file descriptor is available with no callback.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800271 * This function will never return POLL_CALLBACK.
Jeff Brown7901eb22010-09-13 23:17:30 -0700272 */
Jeff Brown905682a2010-09-16 18:28:12 -0700273 int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
274 inline int pollAll(int timeoutMillis) {
275 return pollAll(timeoutMillis, NULL, NULL, NULL);
276 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700277
278 /**
279 * Wakes the poll asynchronously.
280 *
281 * This method can be called on any thread.
282 * This method returns immediately.
283 */
284 void wake();
285
286 /**
287 * Adds a new file descriptor to be polled by the looper.
288 * If the same file descriptor was previously added, it is replaced.
289 *
290 * "fd" is the file descriptor to be added.
Jeff Browndd1b0372012-05-31 16:15:35 -0700291 * "ident" is an identifier for this event, which is returned from pollOnce().
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800292 * The identifier must be >= 0, or POLL_CALLBACK if providing a non-NULL callback.
293 * "events" are the poll events to wake up on. Typically this is EVENT_INPUT.
Jeff Brown7901eb22010-09-13 23:17:30 -0700294 * "callback" is the function to call when there is an event on the file descriptor.
295 * "data" is a private data pointer to supply to the callback.
296 *
297 * There are two main uses of this function:
298 *
299 * (1) If "callback" is non-NULL, then this function will be called when there is
300 * data on the file descriptor. It should execute any events it has pending,
301 * appropriately reading from the file descriptor. The 'ident' is ignored in this case.
302 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800303 * (2) If "callback" is NULL, the 'ident' will be returned by Looper_pollOnce
Jeff Brown7901eb22010-09-13 23:17:30 -0700304 * when its file descriptor has data available, requiring the caller to take
305 * care of processing it.
306 *
307 * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
308 *
309 * This method can be called on any thread.
310 * This method may block briefly if it needs to wake the poll.
Jeff Browndd1b0372012-05-31 16:15:35 -0700311 *
312 * The callback may either be specified as a bare function pointer or as a smart
313 * pointer callback object. The smart pointer should be preferred because it is
314 * easier to avoid races when the callback is removed from a different thread.
315 * See removeFd() for details.
Jeff Brown7901eb22010-09-13 23:17:30 -0700316 */
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800317 int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700318 int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700319
320 /**
321 * Removes a previously added file descriptor from the looper.
322 *
323 * When this method returns, it is safe to close the file descriptor since the looper
324 * will no longer have a reference to it. However, it is possible for the callback to
325 * already be running or for it to run one last time if the file descriptor was already
326 * signalled. Calling code is responsible for ensuring that this case is safely handled.
327 * For example, if the callback takes care of removing itself during its own execution either
328 * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
329 * again at any later time unless registered anew.
330 *
Jeff Browndd1b0372012-05-31 16:15:35 -0700331 * A simple way to avoid this problem is to use the version of addFd() that takes
332 * a sp<LooperCallback> instead of a bare function pointer. The LooperCallback will
333 * be released at the appropriate time by the Looper.
334 *
Jeff Brown7901eb22010-09-13 23:17:30 -0700335 * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
336 *
337 * This method can be called on any thread.
338 * This method may block briefly if it needs to wake the poll.
339 */
340 int removeFd(int fd);
341
342 /**
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800343 * Enqueues a message to be processed by the specified handler.
344 *
345 * The handler must not be null.
346 * This method can be called on any thread.
347 */
348 void sendMessage(const sp<MessageHandler>& handler, const Message& message);
349
350 /**
351 * Enqueues a message to be processed by the specified handler after all pending messages
352 * after the specified delay.
353 *
354 * The time delay is specified in uptime nanoseconds.
355 * The handler must not be null.
356 * This method can be called on any thread.
357 */
358 void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
359 const Message& message);
360
361 /**
362 * Enqueues a message to be processed by the specified handler after all pending messages
363 * at the specified time.
364 *
365 * The time is specified in uptime nanoseconds.
366 * The handler must not be null.
367 * This method can be called on any thread.
368 */
369 void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
370 const Message& message);
371
372 /**
373 * Removes all messages for the specified handler from the queue.
374 *
375 * The handler must not be null.
376 * This method can be called on any thread.
377 */
378 void removeMessages(const sp<MessageHandler>& handler);
379
380 /**
381 * Removes all messages of a particular type for the specified handler from the queue.
382 *
383 * The handler must not be null.
384 * This method can be called on any thread.
385 */
386 void removeMessages(const sp<MessageHandler>& handler, int what);
387
388 /**
Dianne Hackborn19159f92013-05-06 14:25:20 -0700389 * Return whether this looper's thread is currently idling -- that is, whether it
390 * stopped waiting for more work to do. Note that this is intrinsically racy, since
391 * its state can change before you get the result back.
392 */
393 bool isIdling() const;
394
395 /**
Jeff Brown7901eb22010-09-13 23:17:30 -0700396 * Prepares a looper associated with the calling thread, and returns it.
397 * If the thread already has a looper, it is returned. Otherwise, a new
398 * one is created, associated with the thread, and returned.
399 *
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800400 * The opts may be PREPARE_ALLOW_NON_CALLBACKS or 0.
Jeff Brown7901eb22010-09-13 23:17:30 -0700401 */
402 static sp<Looper> prepare(int opts);
403
404 /**
405 * Sets the given looper to be associated with the calling thread.
406 * If another looper is already associated with the thread, it is replaced.
407 *
408 * If "looper" is NULL, removes the currently associated looper.
409 */
410 static void setForThread(const sp<Looper>& looper);
411
412 /**
413 * Returns the looper associated with the calling thread, or NULL if
414 * there is not one.
415 */
416 static sp<Looper> getForThread();
417
418private:
419 struct Request {
420 int fd;
421 int ident;
Jeff Browndd1b0372012-05-31 16:15:35 -0700422 sp<LooperCallback> callback;
Jeff Brown7901eb22010-09-13 23:17:30 -0700423 void* data;
424 };
425
426 struct Response {
427 int events;
428 Request request;
429 };
430
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800431 struct MessageEnvelope {
432 MessageEnvelope() : uptime(0) { }
433
434 MessageEnvelope(nsecs_t uptime, const sp<MessageHandler> handler,
435 const Message& message) : uptime(uptime), handler(handler), message(message) {
436 }
437
438 nsecs_t uptime;
439 sp<MessageHandler> handler;
440 Message message;
441 };
442
Jeff Brown7901eb22010-09-13 23:17:30 -0700443 const bool mAllowNonCallbacks; // immutable
444
Jeff Brown7901eb22010-09-13 23:17:30 -0700445 int mWakeReadPipeFd; // immutable
446 int mWakeWritePipeFd; // immutable
Jeff Brown8d15c742010-10-05 15:35:37 -0700447 Mutex mLock;
448
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800449 Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
450 bool mSendingMessage; // guarded by mLock
451
Dianne Hackborn19159f92013-05-06 14:25:20 -0700452 // Whether we are currently waiting for work. Not protected by a lock,
453 // any use of it is racy anyway.
454 volatile bool mIdling;
455
Jeff Brown8d15c742010-10-05 15:35:37 -0700456 int mEpollFd; // immutable
Jeff Brown7901eb22010-09-13 23:17:30 -0700457
458 // Locked list of file descriptor monitoring requests.
Jeff Brown8d15c742010-10-05 15:35:37 -0700459 KeyedVector<int, Request> mRequests; // guarded by mLock
Jeff Brown8d15c742010-10-05 15:35:37 -0700460
Jeff Brown7901eb22010-09-13 23:17:30 -0700461 // This state is only used privately by pollOnce and does not require a lock since
462 // it runs on a single thread.
463 Vector<Response> mResponses;
464 size_t mResponseIndex;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800465 nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
Jeff Brown7901eb22010-09-13 23:17:30 -0700466
467 int pollInner(int timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700468 void awoken();
469 void pushResponse(int events, const Request& request);
Jeff Brown7901eb22010-09-13 23:17:30 -0700470
Jeff Brownd1805182010-09-21 15:11:18 -0700471 static void initTLSKey();
Jeff Brown7901eb22010-09-13 23:17:30 -0700472 static void threadDestructor(void *st);
473};
474
475} // namespace android
476
477#endif // UTILS_LOOPER_H