blob: 14e3e35c7f885289eaa5351e79cf705cdbf8b7c7 [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>
Alessio Balsini14062072019-05-11 14:29:28 +010017
Mathias Agopian22dbf392017-02-28 15:06:51 -080018#include <sys/eventfd.h>
Alessio Balsini14062072019-05-11 14:29:28 +010019#include <cinttypes>
Jeff Brown7901eb22010-09-13 23:17:30 -070020
21namespace android {
22
Jeff Brown3e2e38b2011-03-02 14:41:58 -080023// --- WeakMessageHandler ---
24
25WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
26 mHandler(handler) {
27}
28
Jeff Browndd1b0372012-05-31 16:15:35 -070029WeakMessageHandler::~WeakMessageHandler() {
30}
31
Jeff Brown3e2e38b2011-03-02 14:41:58 -080032void WeakMessageHandler::handleMessage(const Message& message) {
33 sp<MessageHandler> handler = mHandler.promote();
Yi Konge1731a42018-07-16 18:11:34 -070034 if (handler != nullptr) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -080035 handler->handleMessage(message);
36 }
37}
38
39
Jeff Browndd1b0372012-05-31 16:15:35 -070040// --- SimpleLooperCallback ---
41
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080042SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070043 mCallback(callback) {
44}
45
46SimpleLooperCallback::~SimpleLooperCallback() {
47}
48
49int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
50 return mCallback(fd, events, data);
51}
52
53
Jeff Brown3e2e38b2011-03-02 14:41:58 -080054// --- Looper ---
55
Jeff Brown7901eb22010-09-13 23:17:30 -070056// Maximum number of file descriptors for which to retrieve poll events each iteration.
57static const int EPOLL_MAX_EVENTS = 16;
58
Jeff Brownd1805182010-09-21 15:11:18 -070059static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
60static pthread_key_t gTLSKey = 0;
61
Josh Gao2d08ae52018-07-18 17:26:24 -070062Looper::Looper(bool allowNonCallbacks)
63 : mAllowNonCallbacks(allowNonCallbacks),
64 mSendingMessage(false),
65 mPolling(false),
66 mEpollRebuildRequired(false),
67 mNextRequestSeq(0),
68 mResponseIndex(0),
69 mNextMessageUptime(LLONG_MAX) {
70 mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
71 LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070072
Jeff Browne7d54f82015-03-12 19:32:39 -070073 AutoMutex _l(mLock);
74 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070075}
76
77Looper::~Looper() {
Jeff Brown7901eb22010-09-13 23:17:30 -070078}
79
Jeff Brownd1805182010-09-21 15:11:18 -070080void Looper::initTLSKey() {
Elliott Hughesfd121602019-04-01 12:22:55 -070081 int error = pthread_key_create(&gTLSKey, threadDestructor);
82 LOG_ALWAYS_FATAL_IF(error != 0, "Could not allocate TLS key: %s", strerror(error));
Jeff Brownd1805182010-09-21 15:11:18 -070083}
84
Jeff Brown7901eb22010-09-13 23:17:30 -070085void Looper::threadDestructor(void *st) {
86 Looper* const self = static_cast<Looper*>(st);
Yi Konge1731a42018-07-16 18:11:34 -070087 if (self != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070088 self->decStrong((void*)threadDestructor);
89 }
90}
91
92void Looper::setForThread(const sp<Looper>& looper) {
93 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
94
Yi Konge1731a42018-07-16 18:11:34 -070095 if (looper != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070096 looper->incStrong((void*)threadDestructor);
97 }
98
Jeff Brownd1805182010-09-21 15:11:18 -070099 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700100
Yi Konge1731a42018-07-16 18:11:34 -0700101 if (old != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700102 old->decStrong((void*)threadDestructor);
103 }
104}
105
106sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700107 int result = pthread_once(& gTLSOnce, initTLSKey);
108 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700109
Jeff Brownd1805182010-09-21 15:11:18 -0700110 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700111}
112
113sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800114 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700115 sp<Looper> looper = Looper::getForThread();
Yi Konge1731a42018-07-16 18:11:34 -0700116 if (looper == nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700117 looper = new Looper(allowNonCallbacks);
118 Looper::setForThread(looper);
119 }
120 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000121 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800122 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700123 }
124 return looper;
125}
126
127bool Looper::getAllowNonCallbacks() const {
128 return mAllowNonCallbacks;
129}
130
Jeff Browne7d54f82015-03-12 19:32:39 -0700131void Looper::rebuildEpollLocked() {
132 // Close old epoll instance if we have one.
133 if (mEpollFd >= 0) {
134#if DEBUG_CALLBACKS
135 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
136#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700137 mEpollFd.reset();
Jeff Browne7d54f82015-03-12 19:32:39 -0700138 }
139
140 // Allocate the new epoll instance and register the wake pipe.
Nick Kralevich0a8b4d12018-12-17 09:35:12 -0800141 mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700142 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700143
144 struct epoll_event eventItem;
145 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
146 eventItem.events = EPOLLIN;
Josh Gao2d08ae52018-07-18 17:26:24 -0700147 eventItem.data.fd = mWakeEventFd.get();
148 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &eventItem);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700149 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
150 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700151
152 for (size_t i = 0; i < mRequests.size(); i++) {
153 const Request& request = mRequests.valueAt(i);
154 struct epoll_event eventItem;
155 request.initEventItem(&eventItem);
156
Josh Gao2d08ae52018-07-18 17:26:24 -0700157 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
Jeff Browne7d54f82015-03-12 19:32:39 -0700158 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700159 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
160 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700161 }
162 }
163}
164
165void Looper::scheduleEpollRebuildLocked() {
166 if (!mEpollRebuildRequired) {
167#if DEBUG_CALLBACKS
168 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
169#endif
170 mEpollRebuildRequired = true;
171 wake();
172 }
173}
174
Jeff Brown7901eb22010-09-13 23:17:30 -0700175int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
176 int result = 0;
177 for (;;) {
178 while (mResponseIndex < mResponses.size()) {
179 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700180 int ident = response.request.ident;
181 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800182 int fd = response.request.fd;
183 int events = response.events;
184 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700185#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000186 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800187 "fd=%d, events=0x%x, data=%p",
188 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700189#endif
Yi Konge1731a42018-07-16 18:11:34 -0700190 if (outFd != nullptr) *outFd = fd;
191 if (outEvents != nullptr) *outEvents = events;
192 if (outData != nullptr) *outData = data;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800193 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700194 }
195 }
196
197 if (result != 0) {
198#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000199 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700200#endif
Yi Konge1731a42018-07-16 18:11:34 -0700201 if (outFd != nullptr) *outFd = 0;
202 if (outEvents != nullptr) *outEvents = 0;
203 if (outData != nullptr) *outData = nullptr;
Jeff Brown7901eb22010-09-13 23:17:30 -0700204 return result;
205 }
206
207 result = pollInner(timeoutMillis);
208 }
209}
210
211int Looper::pollInner(int timeoutMillis) {
212#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000213 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700214#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700215
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800216 // Adjust the timeout based on when the next message is due.
217 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
218 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700219 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
220 if (messageTimeoutMillis >= 0
221 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
222 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800223 }
224#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700225 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800226 this, mNextMessageUptime - now, timeoutMillis);
227#endif
228 }
229
230 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800231 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700232 mResponses.clear();
233 mResponseIndex = 0;
234
Dianne Hackborn19159f92013-05-06 14:25:20 -0700235 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800236 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700237
Jeff Brown7901eb22010-09-13 23:17:30 -0700238 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
Josh Gao2d08ae52018-07-18 17:26:24 -0700239 int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700240
Dianne Hackborn19159f92013-05-06 14:25:20 -0700241 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800242 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700243
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800244 // Acquire lock.
245 mLock.lock();
246
Jeff Browne7d54f82015-03-12 19:32:39 -0700247 // Rebuild epoll set if needed.
248 if (mEpollRebuildRequired) {
249 mEpollRebuildRequired = false;
250 rebuildEpollLocked();
251 goto Done;
252 }
253
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800254 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700255 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700256 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700257 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700258 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700259 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800260 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700261 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700262 }
263
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800264 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700265 if (eventCount == 0) {
266#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000267 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700268#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800269 result = POLL_TIMEOUT;
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 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700274#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000275 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700276#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700277
Jeff Brown9da18102010-09-17 17:01:23 -0700278 for (int i = 0; i < eventCount; i++) {
279 int fd = eventItems[i].data.fd;
280 uint32_t epollEvents = eventItems[i].events;
Josh Gao2d08ae52018-07-18 17:26:24 -0700281 if (fd == mWakeEventFd.get()) {
Jeff Brown9da18102010-09-17 17:01:23 -0700282 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700283 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700284 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700285 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700286 }
287 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700288 ssize_t requestIndex = mRequests.indexOfKey(fd);
289 if (requestIndex >= 0) {
290 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800291 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
292 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
293 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
294 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700295 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700296 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000297 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700298 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700299 }
300 }
301 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700302Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700303
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800304 // Invoke pending message callbacks.
305 mNextMessageUptime = LLONG_MAX;
306 while (mMessageEnvelopes.size() != 0) {
307 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
308 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
309 if (messageEnvelope.uptime <= now) {
310 // Remove the envelope from the list.
311 // We keep a strong reference to the handler until the call to handleMessage
312 // finishes. Then we drop it so that the handler can be deleted *before*
313 // we reacquire our lock.
314 { // obtain handler
315 sp<MessageHandler> handler = messageEnvelope.handler;
316 Message message = messageEnvelope.message;
317 mMessageEnvelopes.removeAt(0);
318 mSendingMessage = true;
319 mLock.unlock();
320
321#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000322 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800323 this, handler.get(), message.what);
324#endif
325 handler->handleMessage(message);
326 } // release handler
327
328 mLock.lock();
329 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800330 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800331 } else {
332 // The last message left at the head of the queue determines the next wakeup time.
333 mNextMessageUptime = messageEnvelope.uptime;
334 break;
335 }
336 }
337
338 // Release lock.
339 mLock.unlock();
340
341 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700342 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700343 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800344 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800345 int fd = response.request.fd;
346 int events = response.events;
347 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700348#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000349 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700350 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700351#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700352 // Invoke the callback. Note that the file descriptor may be closed by
353 // the callback (and potentially even reused) before the function returns so
354 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700355 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700356 if (callbackResult == 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700357 removeFd(fd, response.request.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700358 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700359
Jeff Browndd1b0372012-05-31 16:15:35 -0700360 // Clear the callback reference in the response structure promptly because we
361 // will not clear the response vector itself until the next poll.
362 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800363 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700364 }
365 }
366 return result;
367}
368
369int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
370 if (timeoutMillis <= 0) {
371 int result;
372 do {
373 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800374 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700375 return result;
376 } else {
377 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
378 + milliseconds_to_nanoseconds(timeoutMillis);
379
380 for (;;) {
381 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800382 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700383 return result;
384 }
385
Jeff Brown43550ee2011-03-17 01:34:19 -0700386 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
387 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
388 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800389 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700390 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700391 }
392 }
393}
394
395void Looper::wake() {
396#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000397 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700398#endif
399
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700400 uint64_t inc = 1;
Josh Gao2d08ae52018-07-18 17:26:24 -0700401 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700402 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700403 if (errno != EAGAIN) {
Elliott Hughesfd121602019-04-01 12:22:55 -0700404 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
405 mWakeEventFd.get(), nWrite, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700406 }
407 }
408}
409
Jeff Brown8d15c742010-10-05 15:35:37 -0700410void Looper::awoken() {
411#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000412 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700413#endif
414
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700415 uint64_t counter;
Josh Gao2d08ae52018-07-18 17:26:24 -0700416 TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700417}
418
419void Looper::pushResponse(int events, const Request& request) {
420 Response response;
421 response.events = events;
422 response.request = request;
423 mResponses.push(response);
424}
425
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800426int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Yi Konge1731a42018-07-16 18:11:34 -0700427 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : nullptr, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700428}
429
430int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700431#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000432 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700433 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700434#endif
435
Jeff Browndd1b0372012-05-31 16:15:35 -0700436 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700437 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000438 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700439 return -1;
440 }
441
442 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700443 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700444 return -1;
445 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700446 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800447 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700448 }
449
450 { // acquire lock
451 AutoMutex _l(mLock);
452
453 Request request;
454 request.fd = fd;
455 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700456 request.events = events;
457 request.seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700458 request.callback = callback;
459 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700460 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700461
462 struct epoll_event eventItem;
Jeff Browne7d54f82015-03-12 19:32:39 -0700463 request.initEventItem(&eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700464
465 ssize_t requestIndex = mRequests.indexOfKey(fd);
466 if (requestIndex < 0) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700467 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700468 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700469 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700470 return -1;
471 }
472 mRequests.add(fd, request);
473 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700474 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700475 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700476 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700477 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700478 // closed before its callback was unregistered and meanwhile a new
479 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700480 // being registered for the first time. This error may occur naturally
481 // when a callback has the side-effect of closing the file descriptor
482 // before returning and unregistering itself. Callback sequence number
483 // checks further ensure that the race is benign.
484 //
485 // Unfortunately due to kernel limitations we need to rebuild the epoll
486 // set from scratch because it may contain an old file handle that we are
487 // now unable to remove since its file descriptor is no longer valid.
488 // No such problem would have occurred if we were using the poll system
489 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700490#if DEBUG_CALLBACKS
491 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700492 "being recycled, falling back on EPOLL_CTL_ADD: %s",
493 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700494#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700495 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700496 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700497 ALOGE("Error modifying or adding epoll events for fd %d: %s",
498 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700499 return -1;
500 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700501 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700502 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700503 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700504 return -1;
505 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700506 }
507 mRequests.replaceValueAt(requestIndex, request);
508 }
509 } // release lock
510 return 1;
511}
512
513int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700514 return removeFd(fd, -1);
515}
516
517int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700518#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700519 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700520#endif
521
522 { // acquire lock
523 AutoMutex _l(mLock);
524 ssize_t requestIndex = mRequests.indexOfKey(fd);
525 if (requestIndex < 0) {
526 return 0;
527 }
528
Jeff Brown7a0310e2015-03-10 18:31:12 -0700529 // Check the sequence number if one was given.
530 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
531#if DEBUG_CALLBACKS
532 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
533 this, mRequests.valueAt(requestIndex).seq);
534#endif
535 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700536 }
537
Jeff Brown7a0310e2015-03-10 18:31:12 -0700538 // Always remove the FD from the request map even if an error occurs while
539 // updating the epoll set so that we avoid accidentally leaking callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700540 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700541
Josh Gao2d08ae52018-07-18 17:26:24 -0700542 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700543 if (epollResult < 0) {
544 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700545 // Tolerate EBADF or ENOENT when the sequence number is known because it
Jeff Brown7a0310e2015-03-10 18:31:12 -0700546 // means that the file descriptor was closed before its callback was
Jeff Browne7d54f82015-03-12 19:32:39 -0700547 // unregistered. This error may occur naturally when a callback has the
548 // side-effect of closing the file descriptor before returning and
549 // unregistering itself.
550 //
551 // Unfortunately due to kernel limitations we need to rebuild the epoll
552 // set from scratch because it may contain an old file handle that we are
553 // now unable to remove since its file descriptor is no longer valid.
554 // No such problem would have occurred if we were using the poll system
555 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700556#if DEBUG_CALLBACKS
557 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700558 "being closed: %s", this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700559#endif
Jeff Browne7d54f82015-03-12 19:32:39 -0700560 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700561 } else {
Jeff Brown18a574f2015-05-29 17:40:25 -0700562 // Some other error occurred. This is really weird because it means
563 // our list of callbacks got out of sync with the epoll set somehow.
564 // We defensively rebuild the epoll set to avoid getting spurious
565 // notifications with nowhere to go.
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700566 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown18a574f2015-05-29 17:40:25 -0700567 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700568 return -1;
569 }
570 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700571 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700572 return 1;
573}
574
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800575void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700576 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
577 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800578}
579
580void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
581 const Message& message) {
582 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
583 sendMessageAtTime(now + uptimeDelay, handler, message);
584}
585
586void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
587 const Message& message) {
588#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700589 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800590 this, uptime, handler.get(), message.what);
591#endif
592
593 size_t i = 0;
594 { // acquire lock
595 AutoMutex _l(mLock);
596
597 size_t messageCount = mMessageEnvelopes.size();
598 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
599 i += 1;
600 }
601
602 MessageEnvelope messageEnvelope(uptime, handler, message);
603 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
604
605 // Optimization: If the Looper is currently sending a message, then we can skip
606 // the call to wake() because the next thing the Looper will do after processing
607 // messages is to decide when the next wakeup time should be. In fact, it does
608 // not even matter whether this code is running on the Looper thread.
609 if (mSendingMessage) {
610 return;
611 }
612 } // release lock
613
614 // Wake the poll loop only when we enqueue a new message at the head.
615 if (i == 0) {
616 wake();
617 }
618}
619
620void Looper::removeMessages(const sp<MessageHandler>& handler) {
621#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000622 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800623#endif
624
625 { // acquire lock
626 AutoMutex _l(mLock);
627
628 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
629 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
630 if (messageEnvelope.handler == handler) {
631 mMessageEnvelopes.removeAt(i);
632 }
633 }
634 } // release lock
635}
636
637void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
638#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000639 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800640#endif
641
642 { // acquire lock
643 AutoMutex _l(mLock);
644
645 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
646 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
647 if (messageEnvelope.handler == handler
648 && messageEnvelope.message.what == what) {
649 mMessageEnvelopes.removeAt(i);
650 }
651 }
652 } // release lock
653}
654
Jeff Brown27e57212015-02-26 14:16:30 -0800655bool Looper::isPolling() const {
656 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700657}
658
Jeff Browne7d54f82015-03-12 19:32:39 -0700659void Looper::Request::initEventItem(struct epoll_event* eventItem) const {
660 int epollEvents = 0;
661 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
662 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
663
664 memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
665 eventItem->events = epollEvents;
666 eventItem->data.fd = fd;
667}
668
Colin Cross17b5b822016-09-15 18:15:37 -0700669MessageHandler::~MessageHandler() { }
670
671LooperCallback::~LooperCallback() { }
672
Jeff Brown7901eb22010-09-13 23:17:30 -0700673} // namespace android