blob: ac81090621ab21ad7d09d324e5ad21065f633ba8 [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 Brown7a0310e2015-03-10 18:31:12 -070023#include <inttypes.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070024
25
26namespace android {
27
Jeff Brown3e2e38b2011-03-02 14:41:58 -080028// --- WeakMessageHandler ---
29
30WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
31 mHandler(handler) {
32}
33
Jeff Browndd1b0372012-05-31 16:15:35 -070034WeakMessageHandler::~WeakMessageHandler() {
35}
36
Jeff Brown3e2e38b2011-03-02 14:41:58 -080037void WeakMessageHandler::handleMessage(const Message& message) {
38 sp<MessageHandler> handler = mHandler.promote();
39 if (handler != NULL) {
40 handler->handleMessage(message);
41 }
42}
43
44
Jeff Browndd1b0372012-05-31 16:15:35 -070045// --- SimpleLooperCallback ---
46
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080047SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070048 mCallback(callback) {
49}
50
51SimpleLooperCallback::~SimpleLooperCallback() {
52}
53
54int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
55 return mCallback(fd, events, data);
56}
57
58
Jeff Brown3e2e38b2011-03-02 14:41:58 -080059// --- Looper ---
60
Jeff Brown7901eb22010-09-13 23:17:30 -070061// Hint for number of file descriptors to be associated with the epoll instance.
62static const int EPOLL_SIZE_HINT = 8;
63
64// Maximum number of file descriptors for which to retrieve poll events each iteration.
65static const int EPOLL_MAX_EVENTS = 16;
66
Jeff Brownd1805182010-09-21 15:11:18 -070067static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
68static pthread_key_t gTLSKey = 0;
69
Jeff Brown7901eb22010-09-13 23:17:30 -070070Looper::Looper(bool allowNonCallbacks) :
Jeff Brown3e2e38b2011-03-02 14:41:58 -080071 mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
Jeff Brown7a0310e2015-03-10 18:31:12 -070072 mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
Jeff Brown7901eb22010-09-13 23:17:30 -070073 int wakeFds[2];
74 int result = pipe(wakeFds);
75 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
76
77 mWakeReadPipeFd = wakeFds[0];
78 mWakeWritePipeFd = wakeFds[1];
79
80 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
81 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
82 errno);
83
84 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
85 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
86 errno);
87
Jeff Brown27e57212015-02-26 14:16:30 -080088 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -070089
Jeff Brown8d15c742010-10-05 15:35:37 -070090 // Allocate the epoll instance and register the wake pipe.
91 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
92 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
93
Jeff Brown7901eb22010-09-13 23:17:30 -070094 struct epoll_event eventItem;
Jeff Brownd1805182010-09-21 15:11:18 -070095 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
Jeff Brown7901eb22010-09-13 23:17:30 -070096 eventItem.events = EPOLLIN;
97 eventItem.data.fd = mWakeReadPipeFd;
98 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
99 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
100 errno);
101}
102
103Looper::~Looper() {
104 close(mWakeReadPipeFd);
105 close(mWakeWritePipeFd);
106 close(mEpollFd);
107}
108
Jeff Brownd1805182010-09-21 15:11:18 -0700109void Looper::initTLSKey() {
110 int result = pthread_key_create(& gTLSKey, threadDestructor);
111 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
112}
113
Jeff Brown7901eb22010-09-13 23:17:30 -0700114void Looper::threadDestructor(void *st) {
115 Looper* const self = static_cast<Looper*>(st);
116 if (self != NULL) {
117 self->decStrong((void*)threadDestructor);
118 }
119}
120
121void Looper::setForThread(const sp<Looper>& looper) {
122 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
123
124 if (looper != NULL) {
125 looper->incStrong((void*)threadDestructor);
126 }
127
Jeff Brownd1805182010-09-21 15:11:18 -0700128 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700129
130 if (old != NULL) {
131 old->decStrong((void*)threadDestructor);
132 }
133}
134
135sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700136 int result = pthread_once(& gTLSOnce, initTLSKey);
137 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700138
Jeff Brownd1805182010-09-21 15:11:18 -0700139 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700140}
141
142sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800143 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700144 sp<Looper> looper = Looper::getForThread();
145 if (looper == NULL) {
146 looper = new Looper(allowNonCallbacks);
147 Looper::setForThread(looper);
148 }
149 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000150 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800151 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700152 }
153 return looper;
154}
155
156bool Looper::getAllowNonCallbacks() const {
157 return mAllowNonCallbacks;
158}
159
160int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
161 int result = 0;
162 for (;;) {
163 while (mResponseIndex < mResponses.size()) {
164 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700165 int ident = response.request.ident;
166 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800167 int fd = response.request.fd;
168 int events = response.events;
169 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700170#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000171 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800172 "fd=%d, events=0x%x, data=%p",
173 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700174#endif
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800175 if (outFd != NULL) *outFd = fd;
176 if (outEvents != NULL) *outEvents = events;
177 if (outData != NULL) *outData = data;
178 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700179 }
180 }
181
182 if (result != 0) {
183#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000184 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700185#endif
186 if (outFd != NULL) *outFd = 0;
Jeff Browndd1b0372012-05-31 16:15:35 -0700187 if (outEvents != NULL) *outEvents = 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700188 if (outData != NULL) *outData = NULL;
189 return result;
190 }
191
192 result = pollInner(timeoutMillis);
193 }
194}
195
196int Looper::pollInner(int timeoutMillis) {
197#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000198 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700199#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700200
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800201 // Adjust the timeout based on when the next message is due.
202 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
203 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700204 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
205 if (messageTimeoutMillis >= 0
206 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
207 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800208 }
209#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700210 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800211 this, mNextMessageUptime - now, timeoutMillis);
212#endif
213 }
214
215 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800216 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700217 mResponses.clear();
218 mResponseIndex = 0;
219
Dianne Hackborn19159f92013-05-06 14:25:20 -0700220 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800221 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700222
Jeff Brown7901eb22010-09-13 23:17:30 -0700223 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
224 int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700225
Dianne Hackborn19159f92013-05-06 14:25:20 -0700226 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800227 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700228
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800229 // Acquire lock.
230 mLock.lock();
231
232 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700233 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700234 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700235 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700236 }
Steve Block61d341b2012-01-05 23:22:43 +0000237 ALOGW("Poll failed with an unexpected error, errno=%d", errno);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800238 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700239 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700240 }
241
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800242 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700243 if (eventCount == 0) {
244#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000245 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700246#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800247 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700248 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700249 }
250
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800251 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700252#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000253 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700254#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700255
Jeff Brown9da18102010-09-17 17:01:23 -0700256 for (int i = 0; i < eventCount; i++) {
257 int fd = eventItems[i].data.fd;
258 uint32_t epollEvents = eventItems[i].events;
259 if (fd == mWakeReadPipeFd) {
260 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700261 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700262 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000263 ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700264 }
265 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700266 ssize_t requestIndex = mRequests.indexOfKey(fd);
267 if (requestIndex >= 0) {
268 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800269 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
270 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
271 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
272 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700273 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700274 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000275 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700276 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700277 }
278 }
279 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700280Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700281
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800282 // Invoke pending message callbacks.
283 mNextMessageUptime = LLONG_MAX;
284 while (mMessageEnvelopes.size() != 0) {
285 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
286 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
287 if (messageEnvelope.uptime <= now) {
288 // Remove the envelope from the list.
289 // We keep a strong reference to the handler until the call to handleMessage
290 // finishes. Then we drop it so that the handler can be deleted *before*
291 // we reacquire our lock.
292 { // obtain handler
293 sp<MessageHandler> handler = messageEnvelope.handler;
294 Message message = messageEnvelope.message;
295 mMessageEnvelopes.removeAt(0);
296 mSendingMessage = true;
297 mLock.unlock();
298
299#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000300 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800301 this, handler.get(), message.what);
302#endif
303 handler->handleMessage(message);
304 } // release handler
305
306 mLock.lock();
307 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800308 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800309 } else {
310 // The last message left at the head of the queue determines the next wakeup time.
311 mNextMessageUptime = messageEnvelope.uptime;
312 break;
313 }
314 }
315
316 // Release lock.
317 mLock.unlock();
318
319 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700320 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700321 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800322 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800323 int fd = response.request.fd;
324 int events = response.events;
325 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700326#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000327 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700328 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700329#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700330 // Invoke the callback. Note that the file descriptor may be closed by
331 // the callback (and potentially even reused) before the function returns so
332 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700333 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700334 if (callbackResult == 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700335 removeFd(fd, response.request.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700336 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700337
Jeff Browndd1b0372012-05-31 16:15:35 -0700338 // Clear the callback reference in the response structure promptly because we
339 // will not clear the response vector itself until the next poll.
340 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800341 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700342 }
343 }
344 return result;
345}
346
347int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
348 if (timeoutMillis <= 0) {
349 int result;
350 do {
351 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800352 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700353 return result;
354 } else {
355 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
356 + milliseconds_to_nanoseconds(timeoutMillis);
357
358 for (;;) {
359 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800360 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700361 return result;
362 }
363
Jeff Brown43550ee2011-03-17 01:34:19 -0700364 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
365 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
366 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800367 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700368 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700369 }
370 }
371}
372
373void Looper::wake() {
374#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000375 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700376#endif
377
Jeff Brown171bf9e2010-09-16 17:04:52 -0700378 ssize_t nWrite;
379 do {
380 nWrite = write(mWakeWritePipeFd, "W", 1);
381 } while (nWrite == -1 && errno == EINTR);
382
Jeff Brown7901eb22010-09-13 23:17:30 -0700383 if (nWrite != 1) {
384 if (errno != EAGAIN) {
Steve Block61d341b2012-01-05 23:22:43 +0000385 ALOGW("Could not write wake signal, errno=%d", errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700386 }
387 }
388}
389
Jeff Brown8d15c742010-10-05 15:35:37 -0700390void Looper::awoken() {
391#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000392 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700393#endif
394
Jeff Brown8d15c742010-10-05 15:35:37 -0700395 char buffer[16];
396 ssize_t nRead;
397 do {
398 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
399 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
400}
401
402void Looper::pushResponse(int events, const Request& request) {
403 Response response;
404 response.events = events;
405 response.request = request;
406 mResponses.push(response);
407}
408
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800409int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700410 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);
411}
412
413int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700414#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000415 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700416 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700417#endif
418
Jeff Browndd1b0372012-05-31 16:15:35 -0700419 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700420 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000421 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700422 return -1;
423 }
424
425 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700426 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700427 return -1;
428 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700429 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800430 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700431 }
432
Jeff Brown8d15c742010-10-05 15:35:37 -0700433 int epollEvents = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800434 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
435 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700436
Jeff Brown7901eb22010-09-13 23:17:30 -0700437 { // acquire lock
438 AutoMutex _l(mLock);
439
440 Request request;
441 request.fd = fd;
442 request.ident = ident;
443 request.callback = callback;
444 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700445 request.seq = mNextRequestSeq++;
446 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700447
448 struct epoll_event eventItem;
Jeff Brownd1805182010-09-21 15:11:18 -0700449 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
Jeff Brown7901eb22010-09-13 23:17:30 -0700450 eventItem.events = epollEvents;
451 eventItem.data.fd = fd;
452
453 ssize_t requestIndex = mRequests.indexOfKey(fd);
454 if (requestIndex < 0) {
455 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
456 if (epollResult < 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000457 ALOGE("Error adding epoll events for fd %d, errno=%d", fd, errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700458 return -1;
459 }
460 mRequests.add(fd, request);
461 } else {
462 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
463 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700464 if (errno == ENOENT) {
465 // Ignore ENOENT because it means that the file descriptor was
466 // closed before its callback was unregistered and meanwhile a new
467 // file descriptor with the same number has been created and is now
468 // being registered for the first time. We tolerate the error since
469 // it may occur naturally when a callback has the side-effect of
470 // closing the file descriptor before returning and unregistering itself.
471 // Callback sequence number checks further ensure that the race is benign.
472#if DEBUG_CALLBACKS
473 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
474 "being recycled, falling back on EPOLL_CTL_ADD, errno=%d",
475 this, errno);
476#endif
477 epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
478 if (epollResult < 0) {
479 ALOGE("Error modifying or adding epoll events for fd %d, errno=%d",
480 fd, errno);
481 return -1;
482 }
483 } else {
484 ALOGE("Error modifying epoll events for fd %d, errno=%d", fd, errno);
485 return -1;
486 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700487 }
488 mRequests.replaceValueAt(requestIndex, request);
489 }
490 } // release lock
491 return 1;
492}
493
494int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700495 return removeFd(fd, -1);
496}
497
498int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700499#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700500 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700501#endif
502
503 { // acquire lock
504 AutoMutex _l(mLock);
505 ssize_t requestIndex = mRequests.indexOfKey(fd);
506 if (requestIndex < 0) {
507 return 0;
508 }
509
Jeff Brown7a0310e2015-03-10 18:31:12 -0700510 // Check the sequence number if one was given.
511 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
512#if DEBUG_CALLBACKS
513 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
514 this, mRequests.valueAt(requestIndex).seq);
515#endif
516 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700517 }
518
Jeff Brown7a0310e2015-03-10 18:31:12 -0700519 // Always remove the FD from the request map even if an error occurs while
520 // updating the epoll set so that we avoid accidentally leaking callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700521 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700522
523 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, NULL);
524 if (epollResult < 0) {
525 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
526 // Ignore EBADF or ENOENT when the sequence number is known because it
527 // means that the file descriptor was closed before its callback was
528 // unregistered. We tolerate the error since it may occur naturally when
529 // a callback has the side-effect of closing the file descriptor before
530 // returning and unregistering itself.
531#if DEBUG_CALLBACKS
532 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
533 "being closed, ignoring error, errno=%d", this, errno);
534#endif
535 } else {
536 ALOGE("Error removing epoll events for fd %d, errno=%d", fd, errno);
537 return -1;
538 }
539 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700540 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700541 return 1;
542}
543
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800544void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700545 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
546 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800547}
548
549void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
550 const Message& message) {
551 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
552 sendMessageAtTime(now + uptimeDelay, handler, message);
553}
554
555void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
556 const Message& message) {
557#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700558 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800559 this, uptime, handler.get(), message.what);
560#endif
561
562 size_t i = 0;
563 { // acquire lock
564 AutoMutex _l(mLock);
565
566 size_t messageCount = mMessageEnvelopes.size();
567 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
568 i += 1;
569 }
570
571 MessageEnvelope messageEnvelope(uptime, handler, message);
572 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
573
574 // Optimization: If the Looper is currently sending a message, then we can skip
575 // the call to wake() because the next thing the Looper will do after processing
576 // messages is to decide when the next wakeup time should be. In fact, it does
577 // not even matter whether this code is running on the Looper thread.
578 if (mSendingMessage) {
579 return;
580 }
581 } // release lock
582
583 // Wake the poll loop only when we enqueue a new message at the head.
584 if (i == 0) {
585 wake();
586 }
587}
588
589void Looper::removeMessages(const sp<MessageHandler>& handler) {
590#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000591 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800592#endif
593
594 { // acquire lock
595 AutoMutex _l(mLock);
596
597 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
598 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
599 if (messageEnvelope.handler == handler) {
600 mMessageEnvelopes.removeAt(i);
601 }
602 }
603 } // release lock
604}
605
606void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
607#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000608 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800609#endif
610
611 { // acquire lock
612 AutoMutex _l(mLock);
613
614 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
615 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
616 if (messageEnvelope.handler == handler
617 && messageEnvelope.message.what == what) {
618 mMessageEnvelopes.removeAt(i);
619 }
620 }
621 } // release lock
622}
623
Jeff Brown27e57212015-02-26 14:16:30 -0800624bool Looper::isPolling() const {
625 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700626}
627
Jeff Brown7901eb22010-09-13 23:17:30 -0700628} // namespace android