blob: 292425a4436873e206b5a2dfbc0ffedd87ee4231 [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
Prabir Pradhan729057a2021-08-12 12:36:31 -070023namespace {
24
25constexpr uint64_t WAKE_EVENT_FD_SEQ = 1;
26
27epoll_event createEpollEvent(uint32_t events, uint64_t seq) {
28 return {.events = events, .data = {.u64 = seq}};
29}
30
31} // namespace
32
Jeff Brown3e2e38b2011-03-02 14:41:58 -080033// --- WeakMessageHandler ---
34
35WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
36 mHandler(handler) {
37}
38
Jeff Browndd1b0372012-05-31 16:15:35 -070039WeakMessageHandler::~WeakMessageHandler() {
40}
41
Jeff Brown3e2e38b2011-03-02 14:41:58 -080042void WeakMessageHandler::handleMessage(const Message& message) {
43 sp<MessageHandler> handler = mHandler.promote();
Yi Konge1731a42018-07-16 18:11:34 -070044 if (handler != nullptr) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -080045 handler->handleMessage(message);
46 }
47}
48
49
Jeff Browndd1b0372012-05-31 16:15:35 -070050// --- SimpleLooperCallback ---
51
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080052SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070053 mCallback(callback) {
54}
55
56SimpleLooperCallback::~SimpleLooperCallback() {
57}
58
59int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
60 return mCallback(fd, events, data);
61}
62
63
Jeff Brown3e2e38b2011-03-02 14:41:58 -080064// --- Looper ---
65
Jeff Brown7901eb22010-09-13 23:17:30 -070066// Maximum number of file descriptors for which to retrieve poll events each iteration.
67static const int EPOLL_MAX_EVENTS = 16;
68
Jeff Brownd1805182010-09-21 15:11:18 -070069static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
70static pthread_key_t gTLSKey = 0;
71
Josh Gao2d08ae52018-07-18 17:26:24 -070072Looper::Looper(bool allowNonCallbacks)
73 : mAllowNonCallbacks(allowNonCallbacks),
74 mSendingMessage(false),
75 mPolling(false),
76 mEpollRebuildRequired(false),
Prabir Pradhan729057a2021-08-12 12:36:31 -070077 mNextRequestSeq(WAKE_EVENT_FD_SEQ + 1),
Josh Gao2d08ae52018-07-18 17:26:24 -070078 mResponseIndex(0),
79 mNextMessageUptime(LLONG_MAX) {
80 mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
81 LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070082
Jeff Browne7d54f82015-03-12 19:32:39 -070083 AutoMutex _l(mLock);
84 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070085}
86
87Looper::~Looper() {
Jeff Brown7901eb22010-09-13 23:17:30 -070088}
89
Jeff Brownd1805182010-09-21 15:11:18 -070090void Looper::initTLSKey() {
Elliott Hughesfd121602019-04-01 12:22:55 -070091 int error = pthread_key_create(&gTLSKey, threadDestructor);
92 LOG_ALWAYS_FATAL_IF(error != 0, "Could not allocate TLS key: %s", strerror(error));
Jeff Brownd1805182010-09-21 15:11:18 -070093}
94
Jeff Brown7901eb22010-09-13 23:17:30 -070095void Looper::threadDestructor(void *st) {
96 Looper* const self = static_cast<Looper*>(st);
Yi Konge1731a42018-07-16 18:11:34 -070097 if (self != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070098 self->decStrong((void*)threadDestructor);
99 }
100}
101
102void Looper::setForThread(const sp<Looper>& looper) {
103 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
104
Yi Konge1731a42018-07-16 18:11:34 -0700105 if (looper != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700106 looper->incStrong((void*)threadDestructor);
107 }
108
Jeff Brownd1805182010-09-21 15:11:18 -0700109 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700110
Yi Konge1731a42018-07-16 18:11:34 -0700111 if (old != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700112 old->decStrong((void*)threadDestructor);
113 }
114}
115
116sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700117 int result = pthread_once(& gTLSOnce, initTLSKey);
118 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700119
Jeff Brownd1805182010-09-21 15:11:18 -0700120 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700121}
122
123sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800124 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700125 sp<Looper> looper = Looper::getForThread();
Yi Konge1731a42018-07-16 18:11:34 -0700126 if (looper == nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700127 looper = new Looper(allowNonCallbacks);
128 Looper::setForThread(looper);
129 }
130 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000131 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800132 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700133 }
134 return looper;
135}
136
137bool Looper::getAllowNonCallbacks() const {
138 return mAllowNonCallbacks;
139}
140
Jeff Browne7d54f82015-03-12 19:32:39 -0700141void Looper::rebuildEpollLocked() {
142 // Close old epoll instance if we have one.
143 if (mEpollFd >= 0) {
144#if DEBUG_CALLBACKS
145 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
146#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700147 mEpollFd.reset();
Jeff Browne7d54f82015-03-12 19:32:39 -0700148 }
149
Prabir Pradhan729057a2021-08-12 12:36:31 -0700150 // Allocate the new epoll instance and register the WakeEventFd.
Nick Kralevich0a8b4d12018-12-17 09:35:12 -0800151 mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700152 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700153
Prabir Pradhan729057a2021-08-12 12:36:31 -0700154 epoll_event wakeEvent = createEpollEvent(EPOLLIN, WAKE_EVENT_FD_SEQ);
155 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &wakeEvent);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700156 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
157 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700158
Prabir Pradhan729057a2021-08-12 12:36:31 -0700159 for (const auto& [seq, request] : mRequests) {
160 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
Jeff Browne7d54f82015-03-12 19:32:39 -0700161
Josh Gao2d08ae52018-07-18 17:26:24 -0700162 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
Jeff Browne7d54f82015-03-12 19:32:39 -0700163 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700164 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
165 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700166 }
167 }
168}
169
170void Looper::scheduleEpollRebuildLocked() {
171 if (!mEpollRebuildRequired) {
172#if DEBUG_CALLBACKS
173 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
174#endif
175 mEpollRebuildRequired = true;
176 wake();
177 }
178}
179
Jeff Brown7901eb22010-09-13 23:17:30 -0700180int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
181 int result = 0;
182 for (;;) {
183 while (mResponseIndex < mResponses.size()) {
184 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700185 int ident = response.request.ident;
186 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800187 int fd = response.request.fd;
188 int events = response.events;
189 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700190#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000191 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800192 "fd=%d, events=0x%x, data=%p",
193 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700194#endif
Yi Konge1731a42018-07-16 18:11:34 -0700195 if (outFd != nullptr) *outFd = fd;
196 if (outEvents != nullptr) *outEvents = events;
197 if (outData != nullptr) *outData = data;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800198 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700199 }
200 }
201
202 if (result != 0) {
203#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000204 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700205#endif
Yi Konge1731a42018-07-16 18:11:34 -0700206 if (outFd != nullptr) *outFd = 0;
207 if (outEvents != nullptr) *outEvents = 0;
208 if (outData != nullptr) *outData = nullptr;
Jeff Brown7901eb22010-09-13 23:17:30 -0700209 return result;
210 }
211
212 result = pollInner(timeoutMillis);
213 }
214}
215
216int Looper::pollInner(int timeoutMillis) {
217#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000218 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700219#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700220
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800221 // Adjust the timeout based on when the next message is due.
222 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
223 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700224 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
225 if (messageTimeoutMillis >= 0
226 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
227 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800228 }
229#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700230 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800231 this, mNextMessageUptime - now, timeoutMillis);
232#endif
233 }
234
235 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800236 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700237 mResponses.clear();
238 mResponseIndex = 0;
239
Dianne Hackborn19159f92013-05-06 14:25:20 -0700240 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800241 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700242
Jeff Brown7901eb22010-09-13 23:17:30 -0700243 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
Josh Gao2d08ae52018-07-18 17:26:24 -0700244 int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700245
Dianne Hackborn19159f92013-05-06 14:25:20 -0700246 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800247 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700248
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800249 // Acquire lock.
250 mLock.lock();
251
Jeff Browne7d54f82015-03-12 19:32:39 -0700252 // Rebuild epoll set if needed.
253 if (mEpollRebuildRequired) {
254 mEpollRebuildRequired = false;
255 rebuildEpollLocked();
256 goto Done;
257 }
258
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800259 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700260 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700261 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700262 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700263 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700264 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800265 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700266 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700267 }
268
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800269 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700270 if (eventCount == 0) {
271#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000272 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700273#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800274 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700275 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700276 }
277
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800278 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700279#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000280 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700281#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700282
Jeff Brown9da18102010-09-17 17:01:23 -0700283 for (int i = 0; i < eventCount; i++) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700284 const SequenceNumber seq = eventItems[i].data.u64;
Jeff Brown9da18102010-09-17 17:01:23 -0700285 uint32_t epollEvents = eventItems[i].events;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700286 if (seq == WAKE_EVENT_FD_SEQ) {
Jeff Brown9da18102010-09-17 17:01:23 -0700287 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700288 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700289 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700290 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700291 }
292 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700293 const auto& request_it = mRequests.find(seq);
294 if (request_it != mRequests.end()) {
295 const auto& request = request_it->second;
Jeff Brown9da18102010-09-17 17:01:23 -0700296 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800297 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
298 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
299 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
300 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700301 mResponses.push({.seq = seq, .events = events, .request = request});
Jeff Brown9da18102010-09-17 17:01:23 -0700302 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700303 ALOGW("Ignoring unexpected epoll events 0x%x for sequence number %" PRIu64
304 " that is no longer registered.",
305 epollEvents, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700306 }
307 }
308 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700309Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700310
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800311 // Invoke pending message callbacks.
312 mNextMessageUptime = LLONG_MAX;
313 while (mMessageEnvelopes.size() != 0) {
314 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
315 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
316 if (messageEnvelope.uptime <= now) {
317 // Remove the envelope from the list.
318 // We keep a strong reference to the handler until the call to handleMessage
319 // finishes. Then we drop it so that the handler can be deleted *before*
320 // we reacquire our lock.
321 { // obtain handler
322 sp<MessageHandler> handler = messageEnvelope.handler;
323 Message message = messageEnvelope.message;
324 mMessageEnvelopes.removeAt(0);
325 mSendingMessage = true;
326 mLock.unlock();
327
328#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000329 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800330 this, handler.get(), message.what);
331#endif
332 handler->handleMessage(message);
333 } // release handler
334
335 mLock.lock();
336 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800337 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800338 } else {
339 // The last message left at the head of the queue determines the next wakeup time.
340 mNextMessageUptime = messageEnvelope.uptime;
341 break;
342 }
343 }
344
345 // Release lock.
346 mLock.unlock();
347
348 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700349 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700350 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800351 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800352 int fd = response.request.fd;
353 int events = response.events;
354 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700355#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000356 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700357 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700358#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700359 // Invoke the callback. Note that the file descriptor may be closed by
360 // the callback (and potentially even reused) before the function returns so
361 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700362 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700363 if (callbackResult == 0) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700364 AutoMutex _l(mLock);
365 removeSequenceNumberLocked(response.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700366 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700367
Jeff Browndd1b0372012-05-31 16:15:35 -0700368 // Clear the callback reference in the response structure promptly because we
369 // will not clear the response vector itself until the next poll.
370 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800371 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700372 }
373 }
374 return result;
375}
376
377int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
378 if (timeoutMillis <= 0) {
379 int result;
380 do {
381 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800382 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700383 return result;
384 } else {
385 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
386 + milliseconds_to_nanoseconds(timeoutMillis);
387
388 for (;;) {
389 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800390 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700391 return result;
392 }
393
Jeff Brown43550ee2011-03-17 01:34:19 -0700394 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
395 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
396 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800397 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700398 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700399 }
400 }
401}
402
403void Looper::wake() {
404#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000405 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700406#endif
407
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700408 uint64_t inc = 1;
Josh Gao2d08ae52018-07-18 17:26:24 -0700409 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700410 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700411 if (errno != EAGAIN) {
Elliott Hughesfd121602019-04-01 12:22:55 -0700412 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
413 mWakeEventFd.get(), nWrite, strerror(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;
Josh Gao2d08ae52018-07-18 17:26:24 -0700424 TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700425}
426
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800427int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Yi Konge1731a42018-07-16 18:11:34 -0700428 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : nullptr, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700429}
430
431int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700432#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000433 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700434 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700435#endif
436
Jeff Browndd1b0372012-05-31 16:15:35 -0700437 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700438 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000439 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700440 return -1;
441 }
442
443 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700444 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700445 return -1;
446 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700447 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800448 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700449 }
450
451 { // acquire lock
452 AutoMutex _l(mLock);
Prabir Pradhan729057a2021-08-12 12:36:31 -0700453 // There is a sequence number reserved for the WakeEventFd.
454 if (mNextRequestSeq == WAKE_EVENT_FD_SEQ) mNextRequestSeq++;
455 const SequenceNumber seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700456
457 Request request;
458 request.fd = fd;
459 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700460 request.events = events;
Jeff Brown7901eb22010-09-13 23:17:30 -0700461 request.callback = callback;
462 request.data = data;
463
Prabir Pradhan729057a2021-08-12 12:36:31 -0700464 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
465 auto seq_it = mSequenceNumberByFd.find(fd);
466 if (seq_it == mSequenceNumberByFd.end()) {
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 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700472 mRequests.emplace(seq, request);
473 mSequenceNumberByFd.emplace(fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700474 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700475 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700476 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700477 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700478 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700479 // closed before its callback was unregistered and meanwhile a new
480 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700481 // being registered for the first time. This error may occur naturally
482 // when a callback has the side-effect of closing the file descriptor
483 // before returning and unregistering itself. Callback sequence number
484 // checks further ensure that the race is benign.
485 //
486 // Unfortunately due to kernel limitations we need to rebuild the epoll
487 // set from scratch because it may contain an old file handle that we are
488 // now unable to remove since its file descriptor is no longer valid.
489 // No such problem would have occurred if we were using the poll system
Prabir Pradhan729057a2021-08-12 12:36:31 -0700490 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700491#if DEBUG_CALLBACKS
492 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700493 "being recycled, falling back on EPOLL_CTL_ADD: %s",
494 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700495#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700496 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700497 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700498 ALOGE("Error modifying or adding epoll events for fd %d: %s",
499 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700500 return -1;
501 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700502 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700503 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700504 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700505 return -1;
506 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700507 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700508 const SequenceNumber oldSeq = seq_it->second;
509 mRequests.erase(oldSeq);
510 mRequests.emplace(seq, request);
511 seq_it->second = seq;
Jeff Brown7901eb22010-09-13 23:17:30 -0700512 }
513 } // release lock
514 return 1;
515}
516
517int Looper::removeFd(int fd) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700518 AutoMutex _l(mLock);
519 const auto& it = mSequenceNumberByFd.find(fd);
520 if (it == mSequenceNumberByFd.end()) {
521 return 0;
522 }
523 return removeSequenceNumberLocked(it->second);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700524}
525
Prabir Pradhan729057a2021-08-12 12:36:31 -0700526int Looper::removeSequenceNumberLocked(SequenceNumber seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700527#if DEBUG_CALLBACKS
Prabir Pradhan729057a2021-08-12 12:36:31 -0700528 ALOGD("%p ~ removeFd - fd=%d, seq=%u", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700529#endif
530
Prabir Pradhan729057a2021-08-12 12:36:31 -0700531 const auto& request_it = mRequests.find(seq);
532 if (request_it == mRequests.end()) {
533 return 0;
534 }
535 const int fd = request_it->second.fd;
Jeff Brown7901eb22010-09-13 23:17:30 -0700536
Prabir Pradhan729057a2021-08-12 12:36:31 -0700537 // Always remove the FD from the request map even if an error occurs while
538 // updating the epoll set so that we avoid accidentally leaking callbacks.
539 mRequests.erase(request_it);
540 mSequenceNumberByFd.erase(fd);
541
542 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
543 if (epollResult < 0) {
544 if (errno == EBADF || errno == ENOENT) {
545 // Tolerate EBADF or ENOENT because it means that the file descriptor was closed
546 // before its callback was unregistered. This error may occur naturally when a
547 // callback has the side-effect of closing the file descriptor before returning and
548 // unregistering itself.
549 //
550 // Unfortunately due to kernel limitations we need to rebuild the epoll
551 // set from scratch because it may contain an old file handle that we are
552 // now unable to remove since its file descriptor is no longer valid.
553 // No such problem would have occurred if we were using the poll system
554 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700555#if DEBUG_CALLBACKS
Prabir Pradhan729057a2021-08-12 12:36:31 -0700556 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
557 "being closed: %s",
558 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700559#endif
Prabir Pradhan729057a2021-08-12 12:36:31 -0700560 scheduleEpollRebuildLocked();
561 } else {
562 // 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.
566 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
567 scheduleEpollRebuildLocked();
568 return -1;
Jeff Brown7901eb22010-09-13 23:17:30 -0700569 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700570 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700571 return 1;
572}
573
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800574void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700575 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
576 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800577}
578
579void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
580 const Message& message) {
581 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
582 sendMessageAtTime(now + uptimeDelay, handler, message);
583}
584
585void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
586 const Message& message) {
587#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700588 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800589 this, uptime, handler.get(), message.what);
590#endif
591
592 size_t i = 0;
593 { // acquire lock
594 AutoMutex _l(mLock);
595
596 size_t messageCount = mMessageEnvelopes.size();
597 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
598 i += 1;
599 }
600
601 MessageEnvelope messageEnvelope(uptime, handler, message);
602 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
603
604 // Optimization: If the Looper is currently sending a message, then we can skip
605 // the call to wake() because the next thing the Looper will do after processing
606 // messages is to decide when the next wakeup time should be. In fact, it does
607 // not even matter whether this code is running on the Looper thread.
608 if (mSendingMessage) {
609 return;
610 }
611 } // release lock
612
613 // Wake the poll loop only when we enqueue a new message at the head.
614 if (i == 0) {
615 wake();
616 }
617}
618
619void Looper::removeMessages(const sp<MessageHandler>& handler) {
620#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000621 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800622#endif
623
624 { // acquire lock
625 AutoMutex _l(mLock);
626
627 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
628 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
629 if (messageEnvelope.handler == handler) {
630 mMessageEnvelopes.removeAt(i);
631 }
632 }
633 } // release lock
634}
635
636void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
637#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000638 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800639#endif
640
641 { // acquire lock
642 AutoMutex _l(mLock);
643
644 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
645 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
646 if (messageEnvelope.handler == handler
647 && messageEnvelope.message.what == what) {
648 mMessageEnvelopes.removeAt(i);
649 }
650 }
651 } // release lock
652}
653
Jeff Brown27e57212015-02-26 14:16:30 -0800654bool Looper::isPolling() const {
655 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700656}
657
Prabir Pradhan729057a2021-08-12 12:36:31 -0700658uint32_t Looper::Request::getEpollEvents() const {
659 uint32_t epollEvents = 0;
Jeff Browne7d54f82015-03-12 19:32:39 -0700660 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
661 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700662 return epollEvents;
Jeff Browne7d54f82015-03-12 19:32:39 -0700663}
664
Colin Cross17b5b822016-09-15 18:15:37 -0700665MessageHandler::~MessageHandler() { }
666
667LooperCallback::~LooperCallback() { }
668
Jeff Brown7901eb22010-09-13 23:17:30 -0700669} // namespace android