blob: 9a2dd6cc45ed115be45ce9972b379a9bec184b3a [file] [log] [blame]
Jeff Brown7901eb22010-09-13 23:17:30 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// A looper implementation based on epoll().
5//
6#define LOG_TAG "Looper"
7
8//#define LOG_NDEBUG 0
9
10// Debugs poll and wake interactions.
11#define DEBUG_POLL_AND_WAKE 0
12
13// Debugs callback registration and invocation.
14#define DEBUG_CALLBACKS 0
15
16#include <cutils/log.h>
17#include <utils/Looper.h>
18#include <utils/Timers.h>
19
20#include <unistd.h>
21#include <fcntl.h>
Jeff Brown3e2e38b2011-03-02 14:41:58 -080022#include <limits.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070023
24
25namespace android {
26
Jeff Brown3e2e38b2011-03-02 14:41:58 -080027// --- WeakMessageHandler ---
28
29WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
30 mHandler(handler) {
31}
32
Jeff Browndd1b0372012-05-31 16:15:35 -070033WeakMessageHandler::~WeakMessageHandler() {
34}
35
Jeff Brown3e2e38b2011-03-02 14:41:58 -080036void WeakMessageHandler::handleMessage(const Message& message) {
37 sp<MessageHandler> handler = mHandler.promote();
38 if (handler != NULL) {
39 handler->handleMessage(message);
40 }
41}
42
43
Jeff Browndd1b0372012-05-31 16:15:35 -070044// --- SimpleLooperCallback ---
45
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080046SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070047 mCallback(callback) {
48}
49
50SimpleLooperCallback::~SimpleLooperCallback() {
51}
52
53int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
54 return mCallback(fd, events, data);
55}
56
57
Jeff Brown3e2e38b2011-03-02 14:41:58 -080058// --- Looper ---
59
Jeff Brown7901eb22010-09-13 23:17:30 -070060// Hint for number of file descriptors to be associated with the epoll instance.
61static const int EPOLL_SIZE_HINT = 8;
62
63// Maximum number of file descriptors for which to retrieve poll events each iteration.
64static const int EPOLL_MAX_EVENTS = 16;
65
Jeff Brownd1805182010-09-21 15:11:18 -070066static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
67static pthread_key_t gTLSKey = 0;
68
Jeff Brown7901eb22010-09-13 23:17:30 -070069Looper::Looper(bool allowNonCallbacks) :
Jeff Brown3e2e38b2011-03-02 14:41:58 -080070 mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
71 mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
Jeff Brown7901eb22010-09-13 23:17:30 -070072 int wakeFds[2];
73 int result = pipe(wakeFds);
74 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
75
76 mWakeReadPipeFd = wakeFds[0];
77 mWakeWritePipeFd = wakeFds[1];
78
79 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
80 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
81 errno);
82
83 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
84 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
85 errno);
86
Dianne Hackborn19159f92013-05-06 14:25:20 -070087 mIdling = false;
88
Jeff Brown8d15c742010-10-05 15:35:37 -070089 // Allocate the epoll instance and register the wake pipe.
90 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
91 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
92
Jeff Brown7901eb22010-09-13 23:17:30 -070093 struct epoll_event eventItem;
Jeff Brownd1805182010-09-21 15:11:18 -070094 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
Jeff Brown7901eb22010-09-13 23:17:30 -070095 eventItem.events = EPOLLIN;
96 eventItem.data.fd = mWakeReadPipeFd;
97 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
98 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
99 errno);
100}
101
102Looper::~Looper() {
103 close(mWakeReadPipeFd);
104 close(mWakeWritePipeFd);
105 close(mEpollFd);
106}
107
Jeff Brownd1805182010-09-21 15:11:18 -0700108void Looper::initTLSKey() {
109 int result = pthread_key_create(& gTLSKey, threadDestructor);
110 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
111}
112
Jeff Brown7901eb22010-09-13 23:17:30 -0700113void Looper::threadDestructor(void *st) {
114 Looper* const self = static_cast<Looper*>(st);
115 if (self != NULL) {
116 self->decStrong((void*)threadDestructor);
117 }
118}
119
120void Looper::setForThread(const sp<Looper>& looper) {
121 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
122
123 if (looper != NULL) {
124 looper->incStrong((void*)threadDestructor);
125 }
126
Jeff Brownd1805182010-09-21 15:11:18 -0700127 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700128
129 if (old != NULL) {
130 old->decStrong((void*)threadDestructor);
131 }
132}
133
134sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700135 int result = pthread_once(& gTLSOnce, initTLSKey);
136 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700137
Jeff Brownd1805182010-09-21 15:11:18 -0700138 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700139}
140
141sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800142 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700143 sp<Looper> looper = Looper::getForThread();
144 if (looper == NULL) {
145 looper = new Looper(allowNonCallbacks);
146 Looper::setForThread(looper);
147 }
148 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000149 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800150 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700151 }
152 return looper;
153}
154
155bool Looper::getAllowNonCallbacks() const {
156 return mAllowNonCallbacks;
157}
158
159int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
160 int result = 0;
161 for (;;) {
162 while (mResponseIndex < mResponses.size()) {
163 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700164 int ident = response.request.ident;
165 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800166 int fd = response.request.fd;
167 int events = response.events;
168 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700169#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000170 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800171 "fd=%d, events=0x%x, data=%p",
172 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700173#endif
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800174 if (outFd != NULL) *outFd = fd;
175 if (outEvents != NULL) *outEvents = events;
176 if (outData != NULL) *outData = data;
177 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700178 }
179 }
180
181 if (result != 0) {
182#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000183 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700184#endif
185 if (outFd != NULL) *outFd = 0;
Jeff Browndd1b0372012-05-31 16:15:35 -0700186 if (outEvents != NULL) *outEvents = 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700187 if (outData != NULL) *outData = NULL;
188 return result;
189 }
190
191 result = pollInner(timeoutMillis);
192 }
193}
194
195int Looper::pollInner(int timeoutMillis) {
196#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000197 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700198#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700199
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800200 // Adjust the timeout based on when the next message is due.
201 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
202 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700203 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
204 if (messageTimeoutMillis >= 0
205 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
206 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800207 }
208#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000209 ALOGD("%p ~ pollOnce - next message in %lldns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800210 this, mNextMessageUptime - now, timeoutMillis);
211#endif
212 }
213
214 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800215 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700216 mResponses.clear();
217 mResponseIndex = 0;
218
Dianne Hackborn19159f92013-05-06 14:25:20 -0700219 // We are about to idle.
220 mIdling = true;
221
Jeff Brown7901eb22010-09-13 23:17:30 -0700222 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
223 int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700224
Dianne Hackborn19159f92013-05-06 14:25:20 -0700225 // No longer idling.
226 mIdling = false;
227
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800228 // Acquire lock.
229 mLock.lock();
230
231 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700232 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700233 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700234 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700235 }
Steve Block61d341b2012-01-05 23:22:43 +0000236 ALOGW("Poll failed with an unexpected error, errno=%d", errno);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800237 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700238 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700239 }
240
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800241 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700242 if (eventCount == 0) {
243#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000244 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700245#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800246 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700247 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700248 }
249
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800250 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700251#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000252 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700253#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700254
Jeff Brown9da18102010-09-17 17:01:23 -0700255 for (int i = 0; i < eventCount; i++) {
256 int fd = eventItems[i].data.fd;
257 uint32_t epollEvents = eventItems[i].events;
258 if (fd == mWakeReadPipeFd) {
259 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700260 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700261 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000262 ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700263 }
264 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700265 ssize_t requestIndex = mRequests.indexOfKey(fd);
266 if (requestIndex >= 0) {
267 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800268 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
269 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
270 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
271 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700272 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700273 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000274 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700275 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700276 }
277 }
278 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700279Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700280
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800281 // Invoke pending message callbacks.
282 mNextMessageUptime = LLONG_MAX;
283 while (mMessageEnvelopes.size() != 0) {
284 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
285 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
286 if (messageEnvelope.uptime <= now) {
287 // Remove the envelope from the list.
288 // We keep a strong reference to the handler until the call to handleMessage
289 // finishes. Then we drop it so that the handler can be deleted *before*
290 // we reacquire our lock.
291 { // obtain handler
292 sp<MessageHandler> handler = messageEnvelope.handler;
293 Message message = messageEnvelope.message;
294 mMessageEnvelopes.removeAt(0);
295 mSendingMessage = true;
296 mLock.unlock();
297
298#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000299 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800300 this, handler.get(), message.what);
301#endif
302 handler->handleMessage(message);
303 } // release handler
304
305 mLock.lock();
306 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800307 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800308 } else {
309 // The last message left at the head of the queue determines the next wakeup time.
310 mNextMessageUptime = messageEnvelope.uptime;
311 break;
312 }
313 }
314
315 // Release lock.
316 mLock.unlock();
317
318 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700319 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700320 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800321 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800322 int fd = response.request.fd;
323 int events = response.events;
324 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700325#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000326 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700327 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700328#endif
Jeff Browndd1b0372012-05-31 16:15:35 -0700329 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700330 if (callbackResult == 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800331 removeFd(fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700332 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700333 // Clear the callback reference in the response structure promptly because we
334 // will not clear the response vector itself until the next poll.
335 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800336 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700337 }
338 }
339 return result;
340}
341
342int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
343 if (timeoutMillis <= 0) {
344 int result;
345 do {
346 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800347 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700348 return result;
349 } else {
350 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
351 + milliseconds_to_nanoseconds(timeoutMillis);
352
353 for (;;) {
354 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800355 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700356 return result;
357 }
358
Jeff Brown43550ee2011-03-17 01:34:19 -0700359 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
360 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
361 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800362 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700363 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700364 }
365 }
366}
367
368void Looper::wake() {
369#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000370 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700371#endif
372
Jeff Brown171bf9e2010-09-16 17:04:52 -0700373 ssize_t nWrite;
374 do {
375 nWrite = write(mWakeWritePipeFd, "W", 1);
376 } while (nWrite == -1 && errno == EINTR);
377
Jeff Brown7901eb22010-09-13 23:17:30 -0700378 if (nWrite != 1) {
379 if (errno != EAGAIN) {
Steve Block61d341b2012-01-05 23:22:43 +0000380 ALOGW("Could not write wake signal, errno=%d", errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700381 }
382 }
383}
384
Jeff Brown8d15c742010-10-05 15:35:37 -0700385void Looper::awoken() {
386#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000387 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700388#endif
389
Jeff Brown8d15c742010-10-05 15:35:37 -0700390 char buffer[16];
391 ssize_t nRead;
392 do {
393 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
394 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
395}
396
397void Looper::pushResponse(int events, const Request& request) {
398 Response response;
399 response.events = events;
400 response.request = request;
401 mResponses.push(response);
402}
403
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800404int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700405 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);
406}
407
408int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700409#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000410 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700411 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700412#endif
413
Jeff Browndd1b0372012-05-31 16:15:35 -0700414 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700415 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000416 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700417 return -1;
418 }
419
420 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700421 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700422 return -1;
423 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700424 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800425 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700426 }
427
Jeff Brown8d15c742010-10-05 15:35:37 -0700428 int epollEvents = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800429 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
430 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700431
Jeff Brown7901eb22010-09-13 23:17:30 -0700432 { // acquire lock
433 AutoMutex _l(mLock);
434
435 Request request;
436 request.fd = fd;
437 request.ident = ident;
438 request.callback = callback;
439 request.data = data;
440
441 struct epoll_event eventItem;
Jeff Brownd1805182010-09-21 15:11:18 -0700442 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
Jeff Brown7901eb22010-09-13 23:17:30 -0700443 eventItem.events = epollEvents;
444 eventItem.data.fd = fd;
445
446 ssize_t requestIndex = mRequests.indexOfKey(fd);
447 if (requestIndex < 0) {
448 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
449 if (epollResult < 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000450 ALOGE("Error adding epoll events for fd %d, errno=%d", fd, errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700451 return -1;
452 }
453 mRequests.add(fd, request);
454 } else {
455 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
456 if (epollResult < 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000457 ALOGE("Error modifying epoll events for fd %d, errno=%d", fd, errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700458 return -1;
459 }
460 mRequests.replaceValueAt(requestIndex, request);
461 }
462 } // release lock
463 return 1;
464}
465
466int Looper::removeFd(int fd) {
467#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000468 ALOGD("%p ~ removeFd - fd=%d", this, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700469#endif
470
471 { // acquire lock
472 AutoMutex _l(mLock);
473 ssize_t requestIndex = mRequests.indexOfKey(fd);
474 if (requestIndex < 0) {
475 return 0;
476 }
477
478 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, NULL);
479 if (epollResult < 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000480 ALOGE("Error removing epoll events for fd %d, errno=%d", fd, errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700481 return -1;
482 }
483
484 mRequests.removeItemsAt(requestIndex);
Jeff Brown8d15c742010-10-05 15:35:37 -0700485 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700486 return 1;
487}
488
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800489void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700490 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
491 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800492}
493
494void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
495 const Message& message) {
496 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
497 sendMessageAtTime(now + uptimeDelay, handler, message);
498}
499
500void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
501 const Message& message) {
502#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000503 ALOGD("%p ~ sendMessageAtTime - uptime=%lld, handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800504 this, uptime, handler.get(), message.what);
505#endif
506
507 size_t i = 0;
508 { // acquire lock
509 AutoMutex _l(mLock);
510
511 size_t messageCount = mMessageEnvelopes.size();
512 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
513 i += 1;
514 }
515
516 MessageEnvelope messageEnvelope(uptime, handler, message);
517 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
518
519 // Optimization: If the Looper is currently sending a message, then we can skip
520 // the call to wake() because the next thing the Looper will do after processing
521 // messages is to decide when the next wakeup time should be. In fact, it does
522 // not even matter whether this code is running on the Looper thread.
523 if (mSendingMessage) {
524 return;
525 }
526 } // release lock
527
528 // Wake the poll loop only when we enqueue a new message at the head.
529 if (i == 0) {
530 wake();
531 }
532}
533
534void Looper::removeMessages(const sp<MessageHandler>& handler) {
535#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000536 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800537#endif
538
539 { // acquire lock
540 AutoMutex _l(mLock);
541
542 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
543 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
544 if (messageEnvelope.handler == handler) {
545 mMessageEnvelopes.removeAt(i);
546 }
547 }
548 } // release lock
549}
550
551void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
552#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000553 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800554#endif
555
556 { // acquire lock
557 AutoMutex _l(mLock);
558
559 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
560 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
561 if (messageEnvelope.handler == handler
562 && messageEnvelope.message.what == what) {
563 mMessageEnvelopes.removeAt(i);
564 }
565 }
566 } // release lock
567}
568
Dianne Hackborn19159f92013-05-06 14:25:20 -0700569bool Looper::isIdling() const {
570 return mIdling;
571}
572
Jeff Brown7901eb22010-09-13 23:17:30 -0700573} // namespace android