blob: 5b0ff3a7c802b2c429b2fc14570105966ad571a8 [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>
Tim Kilbourn8892ce62015-03-26 14:36:32 -070024#include <sys/eventfd.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070025
26
27namespace android {
28
Jeff Brown3e2e38b2011-03-02 14:41:58 -080029// --- WeakMessageHandler ---
30
31WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
32 mHandler(handler) {
33}
34
Jeff Browndd1b0372012-05-31 16:15:35 -070035WeakMessageHandler::~WeakMessageHandler() {
36}
37
Jeff Brown3e2e38b2011-03-02 14:41:58 -080038void WeakMessageHandler::handleMessage(const Message& message) {
39 sp<MessageHandler> handler = mHandler.promote();
40 if (handler != NULL) {
41 handler->handleMessage(message);
42 }
43}
44
45
Jeff Browndd1b0372012-05-31 16:15:35 -070046// --- SimpleLooperCallback ---
47
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080048SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070049 mCallback(callback) {
50}
51
52SimpleLooperCallback::~SimpleLooperCallback() {
53}
54
55int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
56 return mCallback(fd, events, data);
57}
58
59
Jeff Brown3e2e38b2011-03-02 14:41:58 -080060// --- Looper ---
61
Jeff Brown7901eb22010-09-13 23:17:30 -070062// Hint for number of file descriptors to be associated with the epoll instance.
63static const int EPOLL_SIZE_HINT = 8;
64
65// Maximum number of file descriptors for which to retrieve poll events each iteration.
66static const int EPOLL_MAX_EVENTS = 16;
67
Jeff Brownd1805182010-09-21 15:11:18 -070068static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
69static pthread_key_t gTLSKey = 0;
70
Jeff Brown7901eb22010-09-13 23:17:30 -070071Looper::Looper(bool allowNonCallbacks) :
Jeff Brown3e2e38b2011-03-02 14:41:58 -080072 mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
Jeff Browne7d54f82015-03-12 19:32:39 -070073 mPolling(false), mEpollFd(-1), mEpollRebuildRequired(false),
Jeff Brown7a0310e2015-03-10 18:31:12 -070074 mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
Tim Kilbourn8892ce62015-03-26 14:36:32 -070075 mWakeEventFd = eventfd(0, EFD_NONBLOCK);
76 LOG_ALWAYS_FATAL_IF(mWakeEventFd < 0, "Could not make wake event fd. errno=%d", errno);
Jeff Brown7901eb22010-09-13 23:17:30 -070077
Jeff Browne7d54f82015-03-12 19:32:39 -070078 AutoMutex _l(mLock);
79 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070080}
81
82Looper::~Looper() {
Tim Kilbourn8892ce62015-03-26 14:36:32 -070083 close(mWakeEventFd);
Jeff Browne7d54f82015-03-12 19:32:39 -070084 if (mEpollFd >= 0) {
85 close(mEpollFd);
86 }
Jeff Brown7901eb22010-09-13 23:17:30 -070087}
88
Jeff Brownd1805182010-09-21 15:11:18 -070089void Looper::initTLSKey() {
90 int result = pthread_key_create(& gTLSKey, threadDestructor);
91 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
92}
93
Jeff Brown7901eb22010-09-13 23:17:30 -070094void Looper::threadDestructor(void *st) {
95 Looper* const self = static_cast<Looper*>(st);
96 if (self != NULL) {
97 self->decStrong((void*)threadDestructor);
98 }
99}
100
101void Looper::setForThread(const sp<Looper>& looper) {
102 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
103
104 if (looper != NULL) {
105 looper->incStrong((void*)threadDestructor);
106 }
107
Jeff Brownd1805182010-09-21 15:11:18 -0700108 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700109
110 if (old != NULL) {
111 old->decStrong((void*)threadDestructor);
112 }
113}
114
115sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700116 int result = pthread_once(& gTLSOnce, initTLSKey);
117 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700118
Jeff Brownd1805182010-09-21 15:11:18 -0700119 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700120}
121
122sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800123 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700124 sp<Looper> looper = Looper::getForThread();
125 if (looper == NULL) {
126 looper = new Looper(allowNonCallbacks);
127 Looper::setForThread(looper);
128 }
129 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000130 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800131 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700132 }
133 return looper;
134}
135
136bool Looper::getAllowNonCallbacks() const {
137 return mAllowNonCallbacks;
138}
139
Jeff Browne7d54f82015-03-12 19:32:39 -0700140void Looper::rebuildEpollLocked() {
141 // Close old epoll instance if we have one.
142 if (mEpollFd >= 0) {
143#if DEBUG_CALLBACKS
144 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
145#endif
146 close(mEpollFd);
147 }
148
149 // Allocate the new epoll instance and register the wake pipe.
150 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
151 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
152
153 struct epoll_event eventItem;
154 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
155 eventItem.events = EPOLLIN;
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700156 eventItem.data.fd = mWakeEventFd;
157 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);
158 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance. errno=%d",
Jeff Browne7d54f82015-03-12 19:32:39 -0700159 errno);
160
161 for (size_t i = 0; i < mRequests.size(); i++) {
162 const Request& request = mRequests.valueAt(i);
163 struct epoll_event eventItem;
164 request.initEventItem(&eventItem);
165
166 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, request.fd, & eventItem);
167 if (epollResult < 0) {
168 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set, errno=%d",
169 request.fd, errno);
170 }
171 }
172}
173
174void Looper::scheduleEpollRebuildLocked() {
175 if (!mEpollRebuildRequired) {
176#if DEBUG_CALLBACKS
177 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
178#endif
179 mEpollRebuildRequired = true;
180 wake();
181 }
182}
183
Jeff Brown7901eb22010-09-13 23:17:30 -0700184int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
185 int result = 0;
186 for (;;) {
187 while (mResponseIndex < mResponses.size()) {
188 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700189 int ident = response.request.ident;
190 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800191 int fd = response.request.fd;
192 int events = response.events;
193 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700194#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000195 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800196 "fd=%d, events=0x%x, data=%p",
197 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700198#endif
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800199 if (outFd != NULL) *outFd = fd;
200 if (outEvents != NULL) *outEvents = events;
201 if (outData != NULL) *outData = data;
202 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700203 }
204 }
205
206 if (result != 0) {
207#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000208 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700209#endif
210 if (outFd != NULL) *outFd = 0;
Jeff Browndd1b0372012-05-31 16:15:35 -0700211 if (outEvents != NULL) *outEvents = 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700212 if (outData != NULL) *outData = NULL;
213 return result;
214 }
215
216 result = pollInner(timeoutMillis);
217 }
218}
219
220int Looper::pollInner(int timeoutMillis) {
221#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000222 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700223#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700224
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800225 // Adjust the timeout based on when the next message is due.
226 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
227 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700228 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
229 if (messageTimeoutMillis >= 0
230 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
231 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800232 }
233#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700234 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800235 this, mNextMessageUptime - now, timeoutMillis);
236#endif
237 }
238
239 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800240 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700241 mResponses.clear();
242 mResponseIndex = 0;
243
Dianne Hackborn19159f92013-05-06 14:25:20 -0700244 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800245 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700246
Jeff Brown7901eb22010-09-13 23:17:30 -0700247 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
248 int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700249
Dianne Hackborn19159f92013-05-06 14:25:20 -0700250 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800251 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700252
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800253 // Acquire lock.
254 mLock.lock();
255
Jeff Browne7d54f82015-03-12 19:32:39 -0700256 // Rebuild epoll set if needed.
257 if (mEpollRebuildRequired) {
258 mEpollRebuildRequired = false;
259 rebuildEpollLocked();
260 goto Done;
261 }
262
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800263 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700264 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700265 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700266 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700267 }
Steve Block61d341b2012-01-05 23:22:43 +0000268 ALOGW("Poll failed with an unexpected error, errno=%d", errno);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800269 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700270 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700271 }
272
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800273 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700274 if (eventCount == 0) {
275#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000276 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700277#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800278 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700279 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700280 }
281
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800282 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700283#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000284 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700285#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700286
Jeff Brown9da18102010-09-17 17:01:23 -0700287 for (int i = 0; i < eventCount; i++) {
288 int fd = eventItems[i].data.fd;
289 uint32_t epollEvents = eventItems[i].events;
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700290 if (fd == mWakeEventFd) {
Jeff Brown9da18102010-09-17 17:01:23 -0700291 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700292 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700293 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700294 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700295 }
296 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700297 ssize_t requestIndex = mRequests.indexOfKey(fd);
298 if (requestIndex >= 0) {
299 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800300 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
301 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
302 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
303 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700304 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700305 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000306 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700307 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700308 }
309 }
310 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700311Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700312
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800313 // Invoke pending message callbacks.
314 mNextMessageUptime = LLONG_MAX;
315 while (mMessageEnvelopes.size() != 0) {
316 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
317 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
318 if (messageEnvelope.uptime <= now) {
319 // Remove the envelope from the list.
320 // We keep a strong reference to the handler until the call to handleMessage
321 // finishes. Then we drop it so that the handler can be deleted *before*
322 // we reacquire our lock.
323 { // obtain handler
324 sp<MessageHandler> handler = messageEnvelope.handler;
325 Message message = messageEnvelope.message;
326 mMessageEnvelopes.removeAt(0);
327 mSendingMessage = true;
328 mLock.unlock();
329
330#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000331 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800332 this, handler.get(), message.what);
333#endif
334 handler->handleMessage(message);
335 } // release handler
336
337 mLock.lock();
338 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800339 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800340 } else {
341 // The last message left at the head of the queue determines the next wakeup time.
342 mNextMessageUptime = messageEnvelope.uptime;
343 break;
344 }
345 }
346
347 // Release lock.
348 mLock.unlock();
349
350 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700351 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700352 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800353 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800354 int fd = response.request.fd;
355 int events = response.events;
356 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700357#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000358 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700359 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700360#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700361 // Invoke the callback. Note that the file descriptor may be closed by
362 // the callback (and potentially even reused) before the function returns so
363 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700364 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700365 if (callbackResult == 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700366 removeFd(fd, response.request.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700367 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700368
Jeff Browndd1b0372012-05-31 16:15:35 -0700369 // Clear the callback reference in the response structure promptly because we
370 // will not clear the response vector itself until the next poll.
371 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800372 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700373 }
374 }
375 return result;
376}
377
378int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
379 if (timeoutMillis <= 0) {
380 int result;
381 do {
382 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800383 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700384 return result;
385 } else {
386 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
387 + milliseconds_to_nanoseconds(timeoutMillis);
388
389 for (;;) {
390 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800391 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700392 return result;
393 }
394
Jeff Brown43550ee2011-03-17 01:34:19 -0700395 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
396 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
397 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800398 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700399 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700400 }
401 }
402}
403
404void Looper::wake() {
405#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000406 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700407#endif
408
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700409 uint64_t inc = 1;
410 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
411 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700412 if (errno != EAGAIN) {
Steve Block61d341b2012-01-05 23:22:43 +0000413 ALOGW("Could not write wake signal, errno=%d", errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700414 }
415 }
416}
417
Jeff Brown8d15c742010-10-05 15:35:37 -0700418void Looper::awoken() {
419#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000420 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700421#endif
422
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700423 uint64_t counter;
424 TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700425}
426
427void Looper::pushResponse(int events, const Request& request) {
428 Response response;
429 response.events = events;
430 response.request = request;
431 mResponses.push(response);
432}
433
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800434int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700435 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);
436}
437
438int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700439#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000440 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700441 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700442#endif
443
Jeff Browndd1b0372012-05-31 16:15:35 -0700444 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700445 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000446 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700447 return -1;
448 }
449
450 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700451 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700452 return -1;
453 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700454 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800455 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700456 }
457
458 { // acquire lock
459 AutoMutex _l(mLock);
460
461 Request request;
462 request.fd = fd;
463 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700464 request.events = events;
465 request.seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700466 request.callback = callback;
467 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700468 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700469
470 struct epoll_event eventItem;
Jeff Browne7d54f82015-03-12 19:32:39 -0700471 request.initEventItem(&eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700472
473 ssize_t requestIndex = mRequests.indexOfKey(fd);
474 if (requestIndex < 0) {
475 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
476 if (epollResult < 0) {
Steve Block1b781ab2012-01-06 19:20:56 +0000477 ALOGE("Error adding epoll events for fd %d, errno=%d", fd, errno);
Jeff Brown7901eb22010-09-13 23:17:30 -0700478 return -1;
479 }
480 mRequests.add(fd, request);
481 } else {
482 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
483 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700484 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700485 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700486 // closed before its callback was unregistered and meanwhile a new
487 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700488 // being registered for the first time. This error may occur naturally
489 // when a callback has the side-effect of closing the file descriptor
490 // before returning and unregistering itself. Callback sequence number
491 // checks further ensure that the race is benign.
492 //
493 // Unfortunately due to kernel limitations we need to rebuild the epoll
494 // set from scratch because it may contain an old file handle that we are
495 // now unable to remove since its file descriptor is no longer valid.
496 // No such problem would have occurred if we were using the poll system
497 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700498#if DEBUG_CALLBACKS
499 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
500 "being recycled, falling back on EPOLL_CTL_ADD, errno=%d",
501 this, errno);
502#endif
503 epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
504 if (epollResult < 0) {
505 ALOGE("Error modifying or adding epoll events for fd %d, errno=%d",
506 fd, errno);
507 return -1;
508 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700509 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700510 } else {
511 ALOGE("Error modifying epoll events for fd %d, errno=%d", fd, errno);
512 return -1;
513 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700514 }
515 mRequests.replaceValueAt(requestIndex, request);
516 }
517 } // release lock
518 return 1;
519}
520
521int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700522 return removeFd(fd, -1);
523}
524
525int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700526#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700527 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700528#endif
529
530 { // acquire lock
531 AutoMutex _l(mLock);
532 ssize_t requestIndex = mRequests.indexOfKey(fd);
533 if (requestIndex < 0) {
534 return 0;
535 }
536
Jeff Brown7a0310e2015-03-10 18:31:12 -0700537 // Check the sequence number if one was given.
538 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
539#if DEBUG_CALLBACKS
540 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
541 this, mRequests.valueAt(requestIndex).seq);
542#endif
543 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700544 }
545
Jeff Brown7a0310e2015-03-10 18:31:12 -0700546 // Always remove the FD from the request map even if an error occurs while
547 // updating the epoll set so that we avoid accidentally leaking callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700548 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700549
550 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, NULL);
551 if (epollResult < 0) {
552 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700553 // Tolerate EBADF or ENOENT when the sequence number is known because it
Jeff Brown7a0310e2015-03-10 18:31:12 -0700554 // means that the file descriptor was closed before its callback was
Jeff Browne7d54f82015-03-12 19:32:39 -0700555 // unregistered. This error may occur naturally when a callback has the
556 // side-effect of closing the file descriptor before returning and
557 // unregistering itself.
558 //
559 // Unfortunately due to kernel limitations we need to rebuild the epoll
560 // set from scratch because it may contain an old file handle that we are
561 // now unable to remove since its file descriptor is no longer valid.
562 // No such problem would have occurred if we were using the poll system
563 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700564#if DEBUG_CALLBACKS
565 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
Jeff Browne7d54f82015-03-12 19:32:39 -0700566 "being closed, errno=%d", this, errno);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700567#endif
Jeff Browne7d54f82015-03-12 19:32:39 -0700568 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700569 } else {
Jeff Brown18a574f2015-05-29 17:40:25 -0700570 // Some other error occurred. This is really weird because it means
571 // our list of callbacks got out of sync with the epoll set somehow.
572 // We defensively rebuild the epoll set to avoid getting spurious
573 // notifications with nowhere to go.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700574 ALOGE("Error removing epoll events for fd %d, errno=%d", fd, errno);
Jeff Brown18a574f2015-05-29 17:40:25 -0700575 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700576 return -1;
577 }
578 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700579 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700580 return 1;
581}
582
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800583void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700584 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
585 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800586}
587
588void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
589 const Message& message) {
590 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
591 sendMessageAtTime(now + uptimeDelay, handler, message);
592}
593
594void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
595 const Message& message) {
596#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700597 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800598 this, uptime, handler.get(), message.what);
599#endif
600
601 size_t i = 0;
602 { // acquire lock
603 AutoMutex _l(mLock);
604
605 size_t messageCount = mMessageEnvelopes.size();
606 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
607 i += 1;
608 }
609
610 MessageEnvelope messageEnvelope(uptime, handler, message);
611 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
612
613 // Optimization: If the Looper is currently sending a message, then we can skip
614 // the call to wake() because the next thing the Looper will do after processing
615 // messages is to decide when the next wakeup time should be. In fact, it does
616 // not even matter whether this code is running on the Looper thread.
617 if (mSendingMessage) {
618 return;
619 }
620 } // release lock
621
622 // Wake the poll loop only when we enqueue a new message at the head.
623 if (i == 0) {
624 wake();
625 }
626}
627
628void Looper::removeMessages(const sp<MessageHandler>& handler) {
629#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000630 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800631#endif
632
633 { // acquire lock
634 AutoMutex _l(mLock);
635
636 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
637 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
638 if (messageEnvelope.handler == handler) {
639 mMessageEnvelopes.removeAt(i);
640 }
641 }
642 } // release lock
643}
644
645void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
646#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000647 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800648#endif
649
650 { // acquire lock
651 AutoMutex _l(mLock);
652
653 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
654 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
655 if (messageEnvelope.handler == handler
656 && messageEnvelope.message.what == what) {
657 mMessageEnvelopes.removeAt(i);
658 }
659 }
660 } // release lock
661}
662
Jeff Brown27e57212015-02-26 14:16:30 -0800663bool Looper::isPolling() const {
664 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700665}
666
Jeff Browne7d54f82015-03-12 19:32:39 -0700667void Looper::Request::initEventItem(struct epoll_event* eventItem) const {
668 int epollEvents = 0;
669 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
670 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
671
672 memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
673 eventItem->events = epollEvents;
674 eventItem->data.fd = fd;
675}
676
Jeff Brown7901eb22010-09-13 23:17:30 -0700677} // namespace android