blob: 6c57b2e540dbebb11d03a52270334460cc9b9df8 [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
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070016#include <utils/Looper.h>
Mathias Agopian22dbf392017-02-28 15:06:51 -080017#include <sys/eventfd.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070018
19namespace android {
20
Jeff Brown3e2e38b2011-03-02 14:41:58 -080021// --- WeakMessageHandler ---
22
23WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
24 mHandler(handler) {
25}
26
Jeff Browndd1b0372012-05-31 16:15:35 -070027WeakMessageHandler::~WeakMessageHandler() {
28}
29
Jeff Brown3e2e38b2011-03-02 14:41:58 -080030void WeakMessageHandler::handleMessage(const Message& message) {
31 sp<MessageHandler> handler = mHandler.promote();
32 if (handler != NULL) {
33 handler->handleMessage(message);
34 }
35}
36
37
Jeff Browndd1b0372012-05-31 16:15:35 -070038// --- SimpleLooperCallback ---
39
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080040SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070041 mCallback(callback) {
42}
43
44SimpleLooperCallback::~SimpleLooperCallback() {
45}
46
47int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
48 return mCallback(fd, events, data);
49}
50
51
Jeff Brown3e2e38b2011-03-02 14:41:58 -080052// --- Looper ---
53
Jeff Brown7901eb22010-09-13 23:17:30 -070054// Hint for number of file descriptors to be associated with the epoll instance.
55static const int EPOLL_SIZE_HINT = 8;
56
57// Maximum number of file descriptors for which to retrieve poll events each iteration.
58static const int EPOLL_MAX_EVENTS = 16;
59
Jeff Brownd1805182010-09-21 15:11:18 -070060static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
61static pthread_key_t gTLSKey = 0;
62
Jeff Brown7901eb22010-09-13 23:17:30 -070063Looper::Looper(bool allowNonCallbacks) :
Jeff Brown3e2e38b2011-03-02 14:41:58 -080064 mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
Jeff Browne7d54f82015-03-12 19:32:39 -070065 mPolling(false), mEpollFd(-1), mEpollRebuildRequired(false),
Jeff Brown7a0310e2015-03-10 18:31:12 -070066 mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
Nick Kralevichc68c8862015-12-18 20:52:37 -080067 mWakeEventFd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Elliott Hughes5b8ff092015-06-30 15:17:14 -070068 LOG_ALWAYS_FATAL_IF(mWakeEventFd < 0, "Could not make wake event fd: %s",
69 strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070070
Jeff Browne7d54f82015-03-12 19:32:39 -070071 AutoMutex _l(mLock);
72 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070073}
74
75Looper::~Looper() {
Tim Kilbourn8892ce62015-03-26 14:36:32 -070076 close(mWakeEventFd);
John Reck48c35db2016-08-23 09:38:25 -070077 mWakeEventFd = -1;
Jeff Browne7d54f82015-03-12 19:32:39 -070078 if (mEpollFd >= 0) {
79 close(mEpollFd);
80 }
Jeff Brown7901eb22010-09-13 23:17:30 -070081}
82
Jeff Brownd1805182010-09-21 15:11:18 -070083void Looper::initTLSKey() {
84 int result = pthread_key_create(& gTLSKey, threadDestructor);
85 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
86}
87
Jeff Brown7901eb22010-09-13 23:17:30 -070088void Looper::threadDestructor(void *st) {
89 Looper* const self = static_cast<Looper*>(st);
90 if (self != NULL) {
91 self->decStrong((void*)threadDestructor);
92 }
93}
94
95void Looper::setForThread(const sp<Looper>& looper) {
96 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
97
98 if (looper != NULL) {
99 looper->incStrong((void*)threadDestructor);
100 }
101
Jeff Brownd1805182010-09-21 15:11:18 -0700102 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700103
104 if (old != NULL) {
105 old->decStrong((void*)threadDestructor);
106 }
107}
108
109sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700110 int result = pthread_once(& gTLSOnce, initTLSKey);
111 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700112
Jeff Brownd1805182010-09-21 15:11:18 -0700113 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700114}
115
116sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800117 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700118 sp<Looper> looper = Looper::getForThread();
119 if (looper == NULL) {
120 looper = new Looper(allowNonCallbacks);
121 Looper::setForThread(looper);
122 }
123 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000124 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800125 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700126 }
127 return looper;
128}
129
130bool Looper::getAllowNonCallbacks() const {
131 return mAllowNonCallbacks;
132}
133
Jeff Browne7d54f82015-03-12 19:32:39 -0700134void Looper::rebuildEpollLocked() {
135 // Close old epoll instance if we have one.
136 if (mEpollFd >= 0) {
137#if DEBUG_CALLBACKS
138 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
139#endif
140 close(mEpollFd);
141 }
142
143 // Allocate the new epoll instance and register the wake pipe.
144 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700145 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700146
147 struct epoll_event eventItem;
148 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
149 eventItem.events = EPOLLIN;
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700150 eventItem.data.fd = mWakeEventFd;
151 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700152 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
153 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700154
155 for (size_t i = 0; i < mRequests.size(); i++) {
156 const Request& request = mRequests.valueAt(i);
157 struct epoll_event eventItem;
158 request.initEventItem(&eventItem);
159
160 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, request.fd, & eventItem);
161 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700162 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
163 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700164 }
165 }
166}
167
168void Looper::scheduleEpollRebuildLocked() {
169 if (!mEpollRebuildRequired) {
170#if DEBUG_CALLBACKS
171 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
172#endif
173 mEpollRebuildRequired = true;
174 wake();
175 }
176}
177
Jeff Brown7901eb22010-09-13 23:17:30 -0700178int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
179 int result = 0;
180 for (;;) {
181 while (mResponseIndex < mResponses.size()) {
182 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700183 int ident = response.request.ident;
184 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800185 int fd = response.request.fd;
186 int events = response.events;
187 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700188#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000189 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800190 "fd=%d, events=0x%x, data=%p",
191 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700192#endif
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800193 if (outFd != NULL) *outFd = fd;
194 if (outEvents != NULL) *outEvents = events;
195 if (outData != NULL) *outData = data;
196 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700197 }
198 }
199
200 if (result != 0) {
201#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000202 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700203#endif
204 if (outFd != NULL) *outFd = 0;
Jeff Browndd1b0372012-05-31 16:15:35 -0700205 if (outEvents != NULL) *outEvents = 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700206 if (outData != NULL) *outData = NULL;
207 return result;
208 }
209
210 result = pollInner(timeoutMillis);
211 }
212}
213
214int Looper::pollInner(int timeoutMillis) {
215#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000216 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700217#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700218
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800219 // Adjust the timeout based on when the next message is due.
220 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
221 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700222 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
223 if (messageTimeoutMillis >= 0
224 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
225 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800226 }
227#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700228 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800229 this, mNextMessageUptime - now, timeoutMillis);
230#endif
231 }
232
233 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800234 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700235 mResponses.clear();
236 mResponseIndex = 0;
237
Dianne Hackborn19159f92013-05-06 14:25:20 -0700238 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800239 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700240
Jeff Brown7901eb22010-09-13 23:17:30 -0700241 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
242 int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700243
Dianne Hackborn19159f92013-05-06 14:25:20 -0700244 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800245 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700246
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800247 // Acquire lock.
248 mLock.lock();
249
Jeff Browne7d54f82015-03-12 19:32:39 -0700250 // Rebuild epoll set if needed.
251 if (mEpollRebuildRequired) {
252 mEpollRebuildRequired = false;
253 rebuildEpollLocked();
254 goto Done;
255 }
256
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800257 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700258 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700259 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700260 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700261 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700262 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800263 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700264 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700265 }
266
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800267 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700268 if (eventCount == 0) {
269#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000270 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700271#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800272 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700273 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700274 }
275
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800276 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700277#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000278 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700279#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700280
Jeff Brown9da18102010-09-17 17:01:23 -0700281 for (int i = 0; i < eventCount; i++) {
282 int fd = eventItems[i].data.fd;
283 uint32_t epollEvents = eventItems[i].events;
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700284 if (fd == mWakeEventFd) {
Jeff Brown9da18102010-09-17 17:01:23 -0700285 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700286 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700287 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700288 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700289 }
290 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700291 ssize_t requestIndex = mRequests.indexOfKey(fd);
292 if (requestIndex >= 0) {
293 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800294 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
295 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
296 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
297 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700298 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700299 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000300 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700301 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700302 }
303 }
304 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700305Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700306
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800307 // Invoke pending message callbacks.
308 mNextMessageUptime = LLONG_MAX;
309 while (mMessageEnvelopes.size() != 0) {
310 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
311 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
312 if (messageEnvelope.uptime <= now) {
313 // Remove the envelope from the list.
314 // We keep a strong reference to the handler until the call to handleMessage
315 // finishes. Then we drop it so that the handler can be deleted *before*
316 // we reacquire our lock.
317 { // obtain handler
318 sp<MessageHandler> handler = messageEnvelope.handler;
319 Message message = messageEnvelope.message;
320 mMessageEnvelopes.removeAt(0);
321 mSendingMessage = true;
322 mLock.unlock();
323
324#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000325 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800326 this, handler.get(), message.what);
327#endif
328 handler->handleMessage(message);
329 } // release handler
330
331 mLock.lock();
332 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800333 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800334 } else {
335 // The last message left at the head of the queue determines the next wakeup time.
336 mNextMessageUptime = messageEnvelope.uptime;
337 break;
338 }
339 }
340
341 // Release lock.
342 mLock.unlock();
343
344 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700345 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700346 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800347 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800348 int fd = response.request.fd;
349 int events = response.events;
350 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700351#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000352 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700353 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700354#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700355 // Invoke the callback. Note that the file descriptor may be closed by
356 // the callback (and potentially even reused) before the function returns so
357 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700358 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700359 if (callbackResult == 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700360 removeFd(fd, response.request.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700361 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700362
Jeff Browndd1b0372012-05-31 16:15:35 -0700363 // Clear the callback reference in the response structure promptly because we
364 // will not clear the response vector itself until the next poll.
365 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800366 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700367 }
368 }
369 return result;
370}
371
372int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
373 if (timeoutMillis <= 0) {
374 int result;
375 do {
376 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800377 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700378 return result;
379 } else {
380 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
381 + milliseconds_to_nanoseconds(timeoutMillis);
382
383 for (;;) {
384 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800385 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700386 return result;
387 }
388
Jeff Brown43550ee2011-03-17 01:34:19 -0700389 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
390 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
391 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800392 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700393 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700394 }
395 }
396}
397
398void Looper::wake() {
399#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000400 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700401#endif
402
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700403 uint64_t inc = 1;
404 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
405 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700406 if (errno != EAGAIN) {
John Reck48c35db2016-08-23 09:38:25 -0700407 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d: %s",
408 mWakeEventFd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700409 }
410 }
411}
412
Jeff Brown8d15c742010-10-05 15:35:37 -0700413void Looper::awoken() {
414#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000415 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700416#endif
417
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700418 uint64_t counter;
419 TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700420}
421
422void Looper::pushResponse(int events, const Request& request) {
423 Response response;
424 response.events = events;
425 response.request = request;
426 mResponses.push(response);
427}
428
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800429int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700430 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);
431}
432
433int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700434#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000435 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700436 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700437#endif
438
Jeff Browndd1b0372012-05-31 16:15:35 -0700439 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700440 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000441 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700442 return -1;
443 }
444
445 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700446 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700447 return -1;
448 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700449 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800450 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700451 }
452
453 { // acquire lock
454 AutoMutex _l(mLock);
455
456 Request request;
457 request.fd = fd;
458 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700459 request.events = events;
460 request.seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700461 request.callback = callback;
462 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700463 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700464
465 struct epoll_event eventItem;
Jeff Browne7d54f82015-03-12 19:32:39 -0700466 request.initEventItem(&eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700467
468 ssize_t requestIndex = mRequests.indexOfKey(fd);
469 if (requestIndex < 0) {
470 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
471 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700472 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700473 return -1;
474 }
475 mRequests.add(fd, request);
476 } else {
477 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
478 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700479 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700480 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700481 // closed before its callback was unregistered and meanwhile a new
482 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700483 // being registered for the first time. This error may occur naturally
484 // when a callback has the side-effect of closing the file descriptor
485 // before returning and unregistering itself. Callback sequence number
486 // checks further ensure that the race is benign.
487 //
488 // Unfortunately due to kernel limitations we need to rebuild the epoll
489 // set from scratch because it may contain an old file handle that we are
490 // now unable to remove since its file descriptor is no longer valid.
491 // No such problem would have occurred if we were using the poll system
492 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700493#if DEBUG_CALLBACKS
494 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700495 "being recycled, falling back on EPOLL_CTL_ADD: %s",
496 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700497#endif
498 epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
499 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700500 ALOGE("Error modifying or adding epoll events for fd %d: %s",
501 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700502 return -1;
503 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700504 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700505 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700506 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700507 return -1;
508 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700509 }
510 mRequests.replaceValueAt(requestIndex, request);
511 }
512 } // release lock
513 return 1;
514}
515
516int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700517 return removeFd(fd, -1);
518}
519
520int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700521#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700522 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700523#endif
524
525 { // acquire lock
526 AutoMutex _l(mLock);
527 ssize_t requestIndex = mRequests.indexOfKey(fd);
528 if (requestIndex < 0) {
529 return 0;
530 }
531
Jeff Brown7a0310e2015-03-10 18:31:12 -0700532 // Check the sequence number if one was given.
533 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
534#if DEBUG_CALLBACKS
535 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
536 this, mRequests.valueAt(requestIndex).seq);
537#endif
538 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700539 }
540
Jeff Brown7a0310e2015-03-10 18:31:12 -0700541 // Always remove the FD from the request map even if an error occurs while
542 // updating the epoll set so that we avoid accidentally leaking callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700543 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700544
545 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, NULL);
546 if (epollResult < 0) {
547 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700548 // Tolerate EBADF or ENOENT when the sequence number is known because it
Jeff Brown7a0310e2015-03-10 18:31:12 -0700549 // means that the file descriptor was closed before its callback was
Jeff Browne7d54f82015-03-12 19:32:39 -0700550 // unregistered. This error may occur naturally when a callback has the
551 // side-effect of closing the file descriptor before returning and
552 // unregistering itself.
553 //
554 // Unfortunately due to kernel limitations we need to rebuild the epoll
555 // set from scratch because it may contain an old file handle that we are
556 // now unable to remove since its file descriptor is no longer valid.
557 // No such problem would have occurred if we were using the poll system
558 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700559#if DEBUG_CALLBACKS
560 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700561 "being closed: %s", this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700562#endif
Jeff Browne7d54f82015-03-12 19:32:39 -0700563 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700564 } else {
Jeff Brown18a574f2015-05-29 17:40:25 -0700565 // Some other error occurred. This is really weird because it means
566 // our list of callbacks got out of sync with the epoll set somehow.
567 // We defensively rebuild the epoll set to avoid getting spurious
568 // notifications with nowhere to go.
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700569 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown18a574f2015-05-29 17:40:25 -0700570 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700571 return -1;
572 }
573 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700574 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700575 return 1;
576}
577
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800578void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700579 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
580 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800581}
582
583void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
584 const Message& message) {
585 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
586 sendMessageAtTime(now + uptimeDelay, handler, message);
587}
588
589void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
590 const Message& message) {
591#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700592 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800593 this, uptime, handler.get(), message.what);
594#endif
595
596 size_t i = 0;
597 { // acquire lock
598 AutoMutex _l(mLock);
599
600 size_t messageCount = mMessageEnvelopes.size();
601 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
602 i += 1;
603 }
604
605 MessageEnvelope messageEnvelope(uptime, handler, message);
606 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
607
608 // Optimization: If the Looper is currently sending a message, then we can skip
609 // the call to wake() because the next thing the Looper will do after processing
610 // messages is to decide when the next wakeup time should be. In fact, it does
611 // not even matter whether this code is running on the Looper thread.
612 if (mSendingMessage) {
613 return;
614 }
615 } // release lock
616
617 // Wake the poll loop only when we enqueue a new message at the head.
618 if (i == 0) {
619 wake();
620 }
621}
622
623void Looper::removeMessages(const sp<MessageHandler>& handler) {
624#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000625 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800626#endif
627
628 { // acquire lock
629 AutoMutex _l(mLock);
630
631 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
632 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
633 if (messageEnvelope.handler == handler) {
634 mMessageEnvelopes.removeAt(i);
635 }
636 }
637 } // release lock
638}
639
640void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
641#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000642 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800643#endif
644
645 { // acquire lock
646 AutoMutex _l(mLock);
647
648 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
649 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
650 if (messageEnvelope.handler == handler
651 && messageEnvelope.message.what == what) {
652 mMessageEnvelopes.removeAt(i);
653 }
654 }
655 } // release lock
656}
657
Jeff Brown27e57212015-02-26 14:16:30 -0800658bool Looper::isPolling() const {
659 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700660}
661
Jeff Browne7d54f82015-03-12 19:32:39 -0700662void Looper::Request::initEventItem(struct epoll_event* eventItem) const {
663 int epollEvents = 0;
664 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
665 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
666
667 memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
668 eventItem->events = epollEvents;
669 eventItem->data.fd = fd;
670}
671
Colin Cross17b5b822016-09-15 18:15:37 -0700672MessageHandler::~MessageHandler() { }
673
674LooperCallback::~LooperCallback() { }
675
Jeff Brown7901eb22010-09-13 23:17:30 -0700676} // namespace android