blob: 402e43cc6a58608c7ef32b29c867d99c048a169f [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.
Steven Moreland377adea2022-10-08 05:06:52 +000011#ifndef DEBUG_POLL_AND_WAKE
Jeff Brown7901eb22010-09-13 23:17:30 -070012#define DEBUG_POLL_AND_WAKE 0
Steven Moreland377adea2022-10-08 05:06:52 +000013#endif
Jeff Brown7901eb22010-09-13 23:17:30 -070014
15// Debugs callback registration and invocation.
Steven Moreland377adea2022-10-08 05:06:52 +000016#ifndef DEBUG_CALLBACKS
Jeff Brown7901eb22010-09-13 23:17:30 -070017#define DEBUG_CALLBACKS 0
Steven Moreland377adea2022-10-08 05:06:52 +000018#endif
Jeff Brown7901eb22010-09-13 23:17:30 -070019
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070020#include <utils/Looper.h>
Alessio Balsini14062072019-05-11 14:29:28 +010021
Mathias Agopian22dbf392017-02-28 15:06:51 -080022#include <sys/eventfd.h>
Alessio Balsini14062072019-05-11 14:29:28 +010023#include <cinttypes>
Jeff Brown7901eb22010-09-13 23:17:30 -070024
25namespace android {
26
Prabir Pradhan729057a2021-08-12 12:36:31 -070027namespace {
28
29constexpr uint64_t WAKE_EVENT_FD_SEQ = 1;
30
31epoll_event createEpollEvent(uint32_t events, uint64_t seq) {
32 return {.events = events, .data = {.u64 = seq}};
33}
34
35} // namespace
36
Jeff Brown3e2e38b2011-03-02 14:41:58 -080037// --- WeakMessageHandler ---
38
39WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
40 mHandler(handler) {
41}
42
Jeff Browndd1b0372012-05-31 16:15:35 -070043WeakMessageHandler::~WeakMessageHandler() {
44}
45
Jeff Brown3e2e38b2011-03-02 14:41:58 -080046void WeakMessageHandler::handleMessage(const Message& message) {
47 sp<MessageHandler> handler = mHandler.promote();
Yi Konge1731a42018-07-16 18:11:34 -070048 if (handler != nullptr) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -080049 handler->handleMessage(message);
50 }
51}
52
53
Jeff Browndd1b0372012-05-31 16:15:35 -070054// --- SimpleLooperCallback ---
55
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080056SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070057 mCallback(callback) {
58}
59
60SimpleLooperCallback::~SimpleLooperCallback() {
61}
62
63int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
64 return mCallback(fd, events, data);
65}
66
67
Jeff Brown3e2e38b2011-03-02 14:41:58 -080068// --- Looper ---
69
Jeff Brown7901eb22010-09-13 23:17:30 -070070// Maximum number of file descriptors for which to retrieve poll events each iteration.
71static const int EPOLL_MAX_EVENTS = 16;
72
Jeff Brownd1805182010-09-21 15:11:18 -070073static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
74static pthread_key_t gTLSKey = 0;
75
Josh Gao2d08ae52018-07-18 17:26:24 -070076Looper::Looper(bool allowNonCallbacks)
77 : mAllowNonCallbacks(allowNonCallbacks),
78 mSendingMessage(false),
79 mPolling(false),
80 mEpollRebuildRequired(false),
Prabir Pradhan729057a2021-08-12 12:36:31 -070081 mNextRequestSeq(WAKE_EVENT_FD_SEQ + 1),
Josh Gao2d08ae52018-07-18 17:26:24 -070082 mResponseIndex(0),
83 mNextMessageUptime(LLONG_MAX) {
84 mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
85 LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070086
Jeff Browne7d54f82015-03-12 19:32:39 -070087 AutoMutex _l(mLock);
88 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070089}
90
91Looper::~Looper() {
Jeff Brown7901eb22010-09-13 23:17:30 -070092}
93
Jeff Brownd1805182010-09-21 15:11:18 -070094void Looper::initTLSKey() {
Elliott Hughesfd121602019-04-01 12:22:55 -070095 int error = pthread_key_create(&gTLSKey, threadDestructor);
96 LOG_ALWAYS_FATAL_IF(error != 0, "Could not allocate TLS key: %s", strerror(error));
Jeff Brownd1805182010-09-21 15:11:18 -070097}
98
Jeff Brown7901eb22010-09-13 23:17:30 -070099void Looper::threadDestructor(void *st) {
100 Looper* const self = static_cast<Looper*>(st);
Yi Konge1731a42018-07-16 18:11:34 -0700101 if (self != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700102 self->decStrong((void*)threadDestructor);
103 }
104}
105
106void Looper::setForThread(const sp<Looper>& looper) {
107 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
108
Yi Konge1731a42018-07-16 18:11:34 -0700109 if (looper != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700110 looper->incStrong((void*)threadDestructor);
111 }
112
Jeff Brownd1805182010-09-21 15:11:18 -0700113 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700114
Yi Konge1731a42018-07-16 18:11:34 -0700115 if (old != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700116 old->decStrong((void*)threadDestructor);
117 }
118}
119
120sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700121 int result = pthread_once(& gTLSOnce, initTLSKey);
122 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700123
Steven Morelanda06e68c2021-04-27 00:09:23 +0000124 Looper* looper = (Looper*)pthread_getspecific(gTLSKey);
125 return sp<Looper>::fromExisting(looper);
Jeff Brown7901eb22010-09-13 23:17:30 -0700126}
127
128sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800129 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700130 sp<Looper> looper = Looper::getForThread();
Yi Konge1731a42018-07-16 18:11:34 -0700131 if (looper == nullptr) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000132 looper = sp<Looper>::make(allowNonCallbacks);
Jeff Brown7901eb22010-09-13 23:17:30 -0700133 Looper::setForThread(looper);
134 }
135 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000136 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800137 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700138 }
139 return looper;
140}
141
142bool Looper::getAllowNonCallbacks() const {
143 return mAllowNonCallbacks;
144}
145
Jeff Browne7d54f82015-03-12 19:32:39 -0700146void Looper::rebuildEpollLocked() {
147 // Close old epoll instance if we have one.
148 if (mEpollFd >= 0) {
149#if DEBUG_CALLBACKS
150 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
151#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700152 mEpollFd.reset();
Jeff Browne7d54f82015-03-12 19:32:39 -0700153 }
154
Prabir Pradhan729057a2021-08-12 12:36:31 -0700155 // Allocate the new epoll instance and register the WakeEventFd.
Nick Kralevich0a8b4d12018-12-17 09:35:12 -0800156 mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700157 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700158
Prabir Pradhan729057a2021-08-12 12:36:31 -0700159 epoll_event wakeEvent = createEpollEvent(EPOLLIN, WAKE_EVENT_FD_SEQ);
160 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &wakeEvent);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700161 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
162 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700163
Prabir Pradhan729057a2021-08-12 12:36:31 -0700164 for (const auto& [seq, request] : mRequests) {
165 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
Jeff Browne7d54f82015-03-12 19:32:39 -0700166
Josh Gao2d08ae52018-07-18 17:26:24 -0700167 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
Jeff Browne7d54f82015-03-12 19:32:39 -0700168 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700169 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
170 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700171 }
172 }
173}
174
175void Looper::scheduleEpollRebuildLocked() {
176 if (!mEpollRebuildRequired) {
177#if DEBUG_CALLBACKS
178 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
179#endif
180 mEpollRebuildRequired = true;
181 wake();
182 }
183}
184
Jeff Brown7901eb22010-09-13 23:17:30 -0700185int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
186 int result = 0;
187 for (;;) {
188 while (mResponseIndex < mResponses.size()) {
189 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700190 int ident = response.request.ident;
191 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800192 int fd = response.request.fd;
193 int events = response.events;
194 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700195#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000196 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800197 "fd=%d, events=0x%x, data=%p",
198 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700199#endif
Yi Konge1731a42018-07-16 18:11:34 -0700200 if (outFd != nullptr) *outFd = fd;
201 if (outEvents != nullptr) *outEvents = events;
202 if (outData != nullptr) *outData = data;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800203 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700204 }
205 }
206
207 if (result != 0) {
208#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000209 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700210#endif
Yi Konge1731a42018-07-16 18:11:34 -0700211 if (outFd != nullptr) *outFd = 0;
212 if (outEvents != nullptr) *outEvents = 0;
213 if (outData != nullptr) *outData = nullptr;
Jeff Brown7901eb22010-09-13 23:17:30 -0700214 return result;
215 }
216
217 result = pollInner(timeoutMillis);
218 }
219}
220
221int Looper::pollInner(int timeoutMillis) {
222#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000223 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700224#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700225
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800226 // Adjust the timeout based on when the next message is due.
227 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
228 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700229 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
230 if (messageTimeoutMillis >= 0
231 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
232 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800233 }
234#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700235 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800236 this, mNextMessageUptime - now, timeoutMillis);
237#endif
238 }
239
240 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800241 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700242 mResponses.clear();
243 mResponseIndex = 0;
244
Dianne Hackborn19159f92013-05-06 14:25:20 -0700245 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800246 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700247
Jeff Brown7901eb22010-09-13 23:17:30 -0700248 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
Josh Gao2d08ae52018-07-18 17:26:24 -0700249 int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700250
Dianne Hackborn19159f92013-05-06 14:25:20 -0700251 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800252 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700253
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800254 // Acquire lock.
255 mLock.lock();
256
Jeff Browne7d54f82015-03-12 19:32:39 -0700257 // Rebuild epoll set if needed.
258 if (mEpollRebuildRequired) {
259 mEpollRebuildRequired = false;
260 rebuildEpollLocked();
261 goto Done;
262 }
263
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800264 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700265 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700266 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700267 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700268 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700269 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800270 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700271 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700272 }
273
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800274 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700275 if (eventCount == 0) {
276#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000277 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700278#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800279 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700280 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700281 }
282
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800283 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700284#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000285 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700286#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700287
Jeff Brown9da18102010-09-17 17:01:23 -0700288 for (int i = 0; i < eventCount; i++) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700289 const SequenceNumber seq = eventItems[i].data.u64;
Jeff Brown9da18102010-09-17 17:01:23 -0700290 uint32_t epollEvents = eventItems[i].events;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700291 if (seq == WAKE_EVENT_FD_SEQ) {
Jeff Brown9da18102010-09-17 17:01:23 -0700292 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700293 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700294 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700295 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700296 }
297 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700298 const auto& request_it = mRequests.find(seq);
299 if (request_it != mRequests.end()) {
300 const auto& request = request_it->second;
Jeff Brown9da18102010-09-17 17:01:23 -0700301 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800302 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
303 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
304 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
305 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700306 mResponses.push({.seq = seq, .events = events, .request = request});
Jeff Brown9da18102010-09-17 17:01:23 -0700307 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700308 ALOGW("Ignoring unexpected epoll events 0x%x for sequence number %" PRIu64
309 " that is no longer registered.",
310 epollEvents, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700311 }
312 }
313 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700314Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700315
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800316 // Invoke pending message callbacks.
317 mNextMessageUptime = LLONG_MAX;
318 while (mMessageEnvelopes.size() != 0) {
319 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
320 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
321 if (messageEnvelope.uptime <= now) {
322 // Remove the envelope from the list.
323 // We keep a strong reference to the handler until the call to handleMessage
324 // finishes. Then we drop it so that the handler can be deleted *before*
325 // we reacquire our lock.
326 { // obtain handler
327 sp<MessageHandler> handler = messageEnvelope.handler;
328 Message message = messageEnvelope.message;
329 mMessageEnvelopes.removeAt(0);
330 mSendingMessage = true;
331 mLock.unlock();
332
333#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000334 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800335 this, handler.get(), message.what);
336#endif
337 handler->handleMessage(message);
338 } // release handler
339
340 mLock.lock();
341 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800342 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800343 } else {
344 // The last message left at the head of the queue determines the next wakeup time.
345 mNextMessageUptime = messageEnvelope.uptime;
346 break;
347 }
348 }
349
350 // Release lock.
351 mLock.unlock();
352
353 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700354 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700355 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800356 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800357 int fd = response.request.fd;
358 int events = response.events;
359 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700360#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000361 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700362 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700363#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700364 // Invoke the callback. Note that the file descriptor may be closed by
365 // the callback (and potentially even reused) before the function returns so
366 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700367 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700368 if (callbackResult == 0) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700369 AutoMutex _l(mLock);
370 removeSequenceNumberLocked(response.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700371 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700372
Jeff Browndd1b0372012-05-31 16:15:35 -0700373 // Clear the callback reference in the response structure promptly because we
374 // will not clear the response vector itself until the next poll.
375 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800376 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700377 }
378 }
379 return result;
380}
381
382int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
383 if (timeoutMillis <= 0) {
384 int result;
385 do {
386 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800387 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700388 return result;
389 } else {
390 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
391 + milliseconds_to_nanoseconds(timeoutMillis);
392
393 for (;;) {
394 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800395 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700396 return result;
397 }
398
Jeff Brown43550ee2011-03-17 01:34:19 -0700399 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
400 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
401 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800402 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700403 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700404 }
405 }
406}
407
408void Looper::wake() {
409#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000410 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700411#endif
412
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700413 uint64_t inc = 1;
Josh Gao2d08ae52018-07-18 17:26:24 -0700414 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700415 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700416 if (errno != EAGAIN) {
Elliott Hughesfd121602019-04-01 12:22:55 -0700417 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
418 mWakeEventFd.get(), nWrite, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700419 }
420 }
421}
422
Jeff Brown8d15c742010-10-05 15:35:37 -0700423void Looper::awoken() {
424#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000425 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700426#endif
427
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700428 uint64_t counter;
Josh Gao2d08ae52018-07-18 17:26:24 -0700429 TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700430}
431
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800432int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000433 sp<SimpleLooperCallback> looperCallback;
434 if (callback) {
435 looperCallback = sp<SimpleLooperCallback>::make(callback);
436 }
437 return addFd(fd, ident, events, looperCallback, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700438}
439
440int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700441#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000442 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700443 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700444#endif
445
Jeff Browndd1b0372012-05-31 16:15:35 -0700446 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700447 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000448 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700449 return -1;
450 }
451
452 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700453 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700454 return -1;
455 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700456 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800457 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700458 }
459
460 { // acquire lock
461 AutoMutex _l(mLock);
Prabir Pradhan729057a2021-08-12 12:36:31 -0700462 // There is a sequence number reserved for the WakeEventFd.
463 if (mNextRequestSeq == WAKE_EVENT_FD_SEQ) mNextRequestSeq++;
464 const SequenceNumber seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700465
466 Request request;
467 request.fd = fd;
468 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700469 request.events = events;
Jeff Brown7901eb22010-09-13 23:17:30 -0700470 request.callback = callback;
471 request.data = data;
472
Prabir Pradhan729057a2021-08-12 12:36:31 -0700473 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
474 auto seq_it = mSequenceNumberByFd.find(fd);
475 if (seq_it == mSequenceNumberByFd.end()) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700476 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700477 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700478 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700479 return -1;
480 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700481 mRequests.emplace(seq, request);
482 mSequenceNumberByFd.emplace(fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700483 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700484 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700485 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700486 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700487 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700488 // closed before its callback was unregistered and meanwhile a new
489 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700490 // being registered for the first time. This error may occur naturally
491 // when a callback has the side-effect of closing the file descriptor
492 // before returning and unregistering itself. Callback sequence number
493 // checks further ensure that the race is benign.
494 //
495 // Unfortunately due to kernel limitations we need to rebuild the epoll
496 // set from scratch because it may contain an old file handle that we are
497 // now unable to remove since its file descriptor is no longer valid.
498 // No such problem would have occurred if we were using the poll system
Prabir Pradhan729057a2021-08-12 12:36:31 -0700499 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700500#if DEBUG_CALLBACKS
501 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700502 "being recycled, falling back on EPOLL_CTL_ADD: %s",
503 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700504#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700505 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700506 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700507 ALOGE("Error modifying or adding epoll events for fd %d: %s",
508 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700509 return -1;
510 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700511 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700512 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700513 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700514 return -1;
515 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700516 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700517 const SequenceNumber oldSeq = seq_it->second;
518 mRequests.erase(oldSeq);
519 mRequests.emplace(seq, request);
520 seq_it->second = seq;
Jeff Brown7901eb22010-09-13 23:17:30 -0700521 }
522 } // release lock
523 return 1;
524}
525
526int Looper::removeFd(int fd) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700527 AutoMutex _l(mLock);
528 const auto& it = mSequenceNumberByFd.find(fd);
529 if (it == mSequenceNumberByFd.end()) {
530 return 0;
531 }
532 return removeSequenceNumberLocked(it->second);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700533}
534
Prabir Pradhan729057a2021-08-12 12:36:31 -0700535int Looper::removeSequenceNumberLocked(SequenceNumber seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700536#if DEBUG_CALLBACKS
Prabir Pradhan729057a2021-08-12 12:36:31 -0700537 ALOGD("%p ~ removeFd - fd=%d, seq=%u", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700538#endif
539
Prabir Pradhan729057a2021-08-12 12:36:31 -0700540 const auto& request_it = mRequests.find(seq);
541 if (request_it == mRequests.end()) {
542 return 0;
543 }
544 const int fd = request_it->second.fd;
Jeff Brown7901eb22010-09-13 23:17:30 -0700545
Prabir Pradhan729057a2021-08-12 12:36:31 -0700546 // Always remove the FD from the request map even if an error occurs while
547 // updating the epoll set so that we avoid accidentally leaking callbacks.
548 mRequests.erase(request_it);
549 mSequenceNumberByFd.erase(fd);
550
551 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
552 if (epollResult < 0) {
553 if (errno == EBADF || errno == ENOENT) {
554 // Tolerate EBADF or ENOENT because it means that the file descriptor was closed
555 // before its callback was unregistered. This error may occur naturally when a
556 // callback has the side-effect of closing the file descriptor before returning and
557 // unregistering itself.
558 //
559 // Unfortunately due to kernel limitations we need to rebuild the epoll
560 // set from scratch because it may contain an old file handle that we are
561 // now unable to remove since its file descriptor is no longer valid.
562 // No such problem would have occurred if we were using the poll system
563 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700564#if DEBUG_CALLBACKS
Prabir Pradhan729057a2021-08-12 12:36:31 -0700565 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
566 "being closed: %s",
567 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700568#endif
Prabir Pradhan729057a2021-08-12 12:36:31 -0700569 scheduleEpollRebuildLocked();
570 } else {
571 // Some other error occurred. This is really weird because it means
572 // our list of callbacks got out of sync with the epoll set somehow.
573 // We defensively rebuild the epoll set to avoid getting spurious
574 // notifications with nowhere to go.
575 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
576 scheduleEpollRebuildLocked();
577 return -1;
Jeff Brown7901eb22010-09-13 23:17:30 -0700578 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700579 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700580 return 1;
581}
582
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800583void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700584 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
585 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800586}
587
588void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
589 const Message& message) {
590 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
591 sendMessageAtTime(now + uptimeDelay, handler, message);
592}
593
594void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
595 const Message& message) {
596#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700597 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800598 this, uptime, handler.get(), message.what);
599#endif
600
601 size_t i = 0;
602 { // acquire lock
603 AutoMutex _l(mLock);
604
605 size_t messageCount = mMessageEnvelopes.size();
606 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
607 i += 1;
608 }
609
610 MessageEnvelope messageEnvelope(uptime, handler, message);
611 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
612
613 // Optimization: If the Looper is currently sending a message, then we can skip
614 // the call to wake() because the next thing the Looper will do after processing
615 // messages is to decide when the next wakeup time should be. In fact, it does
616 // not even matter whether this code is running on the Looper thread.
617 if (mSendingMessage) {
618 return;
619 }
620 } // release lock
621
622 // Wake the poll loop only when we enqueue a new message at the head.
623 if (i == 0) {
624 wake();
625 }
626}
627
628void Looper::removeMessages(const sp<MessageHandler>& handler) {
629#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000630 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800631#endif
632
633 { // acquire lock
634 AutoMutex _l(mLock);
635
636 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
637 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
638 if (messageEnvelope.handler == handler) {
639 mMessageEnvelopes.removeAt(i);
640 }
641 }
642 } // release lock
643}
644
645void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
646#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000647 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800648#endif
649
650 { // acquire lock
651 AutoMutex _l(mLock);
652
653 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
654 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
655 if (messageEnvelope.handler == handler
656 && messageEnvelope.message.what == what) {
657 mMessageEnvelopes.removeAt(i);
658 }
659 }
660 } // release lock
661}
662
Jeff Brown27e57212015-02-26 14:16:30 -0800663bool Looper::isPolling() const {
664 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700665}
666
Prabir Pradhan729057a2021-08-12 12:36:31 -0700667uint32_t Looper::Request::getEpollEvents() const {
668 uint32_t epollEvents = 0;
Jeff Browne7d54f82015-03-12 19:32:39 -0700669 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
670 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700671 return epollEvents;
Jeff Browne7d54f82015-03-12 19:32:39 -0700672}
673
Colin Cross17b5b822016-09-15 18:15:37 -0700674MessageHandler::~MessageHandler() { }
675
676LooperCallback::~LooperCallback() { }
677
Jeff Brown7901eb22010-09-13 23:17:30 -0700678} // namespace android