blob: e11d1973156a511425cf46dbfdc88f37920490b6 [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
Tomasz Wasilczykd41c0f42024-06-25 10:34:23 -070073thread_local static sp<Looper> gThreadLocalLooper;
Jeff Brownd1805182010-09-21 15:11:18 -070074
Josh Gao2d08ae52018-07-18 17:26:24 -070075Looper::Looper(bool allowNonCallbacks)
76 : mAllowNonCallbacks(allowNonCallbacks),
77 mSendingMessage(false),
78 mPolling(false),
79 mEpollRebuildRequired(false),
Prabir Pradhan729057a2021-08-12 12:36:31 -070080 mNextRequestSeq(WAKE_EVENT_FD_SEQ + 1),
Josh Gao2d08ae52018-07-18 17:26:24 -070081 mResponseIndex(0),
82 mNextMessageUptime(LLONG_MAX) {
83 mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
84 LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070085
Jeff Browne7d54f82015-03-12 19:32:39 -070086 AutoMutex _l(mLock);
87 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070088}
89
90Looper::~Looper() {
Jeff Brown7901eb22010-09-13 23:17:30 -070091}
92
Jeff Brown7901eb22010-09-13 23:17:30 -070093void Looper::setForThread(const sp<Looper>& looper) {
Tomasz Wasilczykd41c0f42024-06-25 10:34:23 -070094 gThreadLocalLooper = looper;
Jeff Brown7901eb22010-09-13 23:17:30 -070095}
96
97sp<Looper> Looper::getForThread() {
Tomasz Wasilczykd41c0f42024-06-25 10:34:23 -070098 return gThreadLocalLooper;
Jeff Brown7901eb22010-09-13 23:17:30 -070099}
100
101sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800102 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700103 sp<Looper> looper = Looper::getForThread();
Yi Konge1731a42018-07-16 18:11:34 -0700104 if (looper == nullptr) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000105 looper = sp<Looper>::make(allowNonCallbacks);
Jeff Brown7901eb22010-09-13 23:17:30 -0700106 Looper::setForThread(looper);
107 }
108 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000109 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800110 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700111 }
112 return looper;
113}
114
115bool Looper::getAllowNonCallbacks() const {
116 return mAllowNonCallbacks;
117}
118
Jeff Browne7d54f82015-03-12 19:32:39 -0700119void Looper::rebuildEpollLocked() {
120 // Close old epoll instance if we have one.
121 if (mEpollFd >= 0) {
122#if DEBUG_CALLBACKS
123 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
124#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700125 mEpollFd.reset();
Jeff Browne7d54f82015-03-12 19:32:39 -0700126 }
127
Prabir Pradhan729057a2021-08-12 12:36:31 -0700128 // Allocate the new epoll instance and register the WakeEventFd.
Nick Kralevich0a8b4d12018-12-17 09:35:12 -0800129 mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700130 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700131
Prabir Pradhan729057a2021-08-12 12:36:31 -0700132 epoll_event wakeEvent = createEpollEvent(EPOLLIN, WAKE_EVENT_FD_SEQ);
133 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &wakeEvent);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700134 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
135 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700136
Prabir Pradhan729057a2021-08-12 12:36:31 -0700137 for (const auto& [seq, request] : mRequests) {
138 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
Jeff Browne7d54f82015-03-12 19:32:39 -0700139
Josh Gao2d08ae52018-07-18 17:26:24 -0700140 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
Jeff Browne7d54f82015-03-12 19:32:39 -0700141 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700142 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
143 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700144 }
145 }
146}
147
148void Looper::scheduleEpollRebuildLocked() {
149 if (!mEpollRebuildRequired) {
150#if DEBUG_CALLBACKS
151 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
152#endif
153 mEpollRebuildRequired = true;
154 wake();
155 }
156}
157
Jeff Brown7901eb22010-09-13 23:17:30 -0700158int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
159 int result = 0;
160 for (;;) {
161 while (mResponseIndex < mResponses.size()) {
162 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700163 int ident = response.request.ident;
164 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800165 int fd = response.request.fd;
166 int events = response.events;
167 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700168#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000169 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800170 "fd=%d, events=0x%x, data=%p",
171 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700172#endif
Yi Konge1731a42018-07-16 18:11:34 -0700173 if (outFd != nullptr) *outFd = fd;
174 if (outEvents != nullptr) *outEvents = events;
175 if (outData != nullptr) *outData = data;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800176 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700177 }
178 }
179
180 if (result != 0) {
181#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000182 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700183#endif
Yi Konge1731a42018-07-16 18:11:34 -0700184 if (outFd != nullptr) *outFd = 0;
185 if (outEvents != nullptr) *outEvents = 0;
186 if (outData != nullptr) *outData = nullptr;
Jeff Brown7901eb22010-09-13 23:17:30 -0700187 return result;
188 }
189
190 result = pollInner(timeoutMillis);
191 }
192}
193
194int Looper::pollInner(int timeoutMillis) {
195#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000196 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700197#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700198
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800199 // Adjust the timeout based on when the next message is due.
200 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
201 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700202 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
203 if (messageTimeoutMillis >= 0
204 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
205 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800206 }
207#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700208 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800209 this, mNextMessageUptime - now, timeoutMillis);
210#endif
211 }
212
213 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800214 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700215 mResponses.clear();
216 mResponseIndex = 0;
217
Dianne Hackborn19159f92013-05-06 14:25:20 -0700218 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800219 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700220
Jeff Brown7901eb22010-09-13 23:17:30 -0700221 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
Josh Gao2d08ae52018-07-18 17:26:24 -0700222 int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700223
Dianne Hackborn19159f92013-05-06 14:25:20 -0700224 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800225 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700226
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800227 // Acquire lock.
228 mLock.lock();
229
Jeff Browne7d54f82015-03-12 19:32:39 -0700230 // Rebuild epoll set if needed.
231 if (mEpollRebuildRequired) {
232 mEpollRebuildRequired = false;
233 rebuildEpollLocked();
234 goto Done;
235 }
236
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800237 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700238 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700239 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700240 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700241 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700242 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800243 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700244 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700245 }
246
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800247 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700248 if (eventCount == 0) {
249#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000250 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700251#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800252 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700253 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700254 }
255
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800256 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700257#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000258 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700259#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700260
Jeff Brown9da18102010-09-17 17:01:23 -0700261 for (int i = 0; i < eventCount; i++) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700262 const SequenceNumber seq = eventItems[i].data.u64;
Jeff Brown9da18102010-09-17 17:01:23 -0700263 uint32_t epollEvents = eventItems[i].events;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700264 if (seq == WAKE_EVENT_FD_SEQ) {
Jeff Brown9da18102010-09-17 17:01:23 -0700265 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700266 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700267 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700268 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700269 }
270 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700271 const auto& request_it = mRequests.find(seq);
272 if (request_it != mRequests.end()) {
273 const auto& request = request_it->second;
Jeff Brown9da18102010-09-17 17:01:23 -0700274 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800275 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
276 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
277 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
278 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700279 mResponses.push({.seq = seq, .events = events, .request = request});
Jeff Brown9da18102010-09-17 17:01:23 -0700280 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700281 ALOGW("Ignoring unexpected epoll events 0x%x for sequence number %" PRIu64
282 " that is no longer registered.",
283 epollEvents, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700284 }
285 }
286 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700287Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700288
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800289 // Invoke pending message callbacks.
290 mNextMessageUptime = LLONG_MAX;
291 while (mMessageEnvelopes.size() != 0) {
292 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
293 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
294 if (messageEnvelope.uptime <= now) {
295 // Remove the envelope from the list.
296 // We keep a strong reference to the handler until the call to handleMessage
297 // finishes. Then we drop it so that the handler can be deleted *before*
298 // we reacquire our lock.
299 { // obtain handler
300 sp<MessageHandler> handler = messageEnvelope.handler;
301 Message message = messageEnvelope.message;
302 mMessageEnvelopes.removeAt(0);
303 mSendingMessage = true;
304 mLock.unlock();
305
306#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000307 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800308 this, handler.get(), message.what);
309#endif
310 handler->handleMessage(message);
311 } // release handler
312
313 mLock.lock();
314 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800315 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800316 } else {
317 // The last message left at the head of the queue determines the next wakeup time.
318 mNextMessageUptime = messageEnvelope.uptime;
319 break;
320 }
321 }
322
323 // Release lock.
324 mLock.unlock();
325
326 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700327 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700328 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800329 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800330 int fd = response.request.fd;
331 int events = response.events;
332 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700333#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000334 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700335 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700336#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700337 // Invoke the callback. Note that the file descriptor may be closed by
338 // the callback (and potentially even reused) before the function returns so
339 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700340 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700341 if (callbackResult == 0) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700342 AutoMutex _l(mLock);
343 removeSequenceNumberLocked(response.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700344 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700345
Jeff Browndd1b0372012-05-31 16:15:35 -0700346 // Clear the callback reference in the response structure promptly because we
347 // will not clear the response vector itself until the next poll.
348 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800349 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700350 }
351 }
352 return result;
353}
354
355int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
356 if (timeoutMillis <= 0) {
357 int result;
358 do {
359 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800360 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700361 return result;
362 } else {
363 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
364 + milliseconds_to_nanoseconds(timeoutMillis);
365
366 for (;;) {
367 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800368 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700369 return result;
370 }
371
Jeff Brown43550ee2011-03-17 01:34:19 -0700372 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
373 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
374 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800375 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700376 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700377 }
378 }
379}
380
381void Looper::wake() {
382#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000383 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700384#endif
385
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700386 uint64_t inc = 1;
Josh Gao2d08ae52018-07-18 17:26:24 -0700387 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700388 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700389 if (errno != EAGAIN) {
Elliott Hughesfd121602019-04-01 12:22:55 -0700390 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
391 mWakeEventFd.get(), nWrite, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700392 }
393 }
394}
395
Jeff Brown8d15c742010-10-05 15:35:37 -0700396void Looper::awoken() {
397#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000398 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700399#endif
400
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700401 uint64_t counter;
Josh Gao2d08ae52018-07-18 17:26:24 -0700402 TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700403}
404
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800405int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000406 sp<SimpleLooperCallback> looperCallback;
407 if (callback) {
408 looperCallback = sp<SimpleLooperCallback>::make(callback);
409 }
410 return addFd(fd, ident, events, looperCallback, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700411}
412
413int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700414#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000415 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700416 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700417#endif
418
Jeff Browndd1b0372012-05-31 16:15:35 -0700419 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700420 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000421 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700422 return -1;
423 }
424
425 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700426 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700427 return -1;
428 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700429 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800430 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700431 }
432
433 { // acquire lock
434 AutoMutex _l(mLock);
Prabir Pradhan729057a2021-08-12 12:36:31 -0700435 // There is a sequence number reserved for the WakeEventFd.
436 if (mNextRequestSeq == WAKE_EVENT_FD_SEQ) mNextRequestSeq++;
437 const SequenceNumber seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700438
439 Request request;
440 request.fd = fd;
441 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700442 request.events = events;
Jeff Brown7901eb22010-09-13 23:17:30 -0700443 request.callback = callback;
444 request.data = data;
445
Prabir Pradhan729057a2021-08-12 12:36:31 -0700446 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
447 auto seq_it = mSequenceNumberByFd.find(fd);
448 if (seq_it == mSequenceNumberByFd.end()) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700449 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700450 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700451 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700452 return -1;
453 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700454 mRequests.emplace(seq, request);
455 mSequenceNumberByFd.emplace(fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700456 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700457 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700458 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700459 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700460 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700461 // closed before its callback was unregistered and meanwhile a new
462 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700463 // being registered for the first time. This error may occur naturally
464 // when a callback has the side-effect of closing the file descriptor
465 // before returning and unregistering itself. Callback sequence number
466 // checks further ensure that the race is benign.
467 //
468 // Unfortunately due to kernel limitations we need to rebuild the epoll
469 // set from scratch because it may contain an old file handle that we are
470 // now unable to remove since its file descriptor is no longer valid.
471 // No such problem would have occurred if we were using the poll system
Prabir Pradhan729057a2021-08-12 12:36:31 -0700472 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700473#if DEBUG_CALLBACKS
474 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700475 "being recycled, falling back on EPOLL_CTL_ADD: %s",
476 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700477#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700478 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700479 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700480 ALOGE("Error modifying or adding epoll events for fd %d: %s",
481 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700482 return -1;
483 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700484 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700485 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700486 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700487 return -1;
488 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700489 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700490 const SequenceNumber oldSeq = seq_it->second;
491 mRequests.erase(oldSeq);
492 mRequests.emplace(seq, request);
493 seq_it->second = seq;
Jeff Brown7901eb22010-09-13 23:17:30 -0700494 }
495 } // release lock
496 return 1;
497}
498
499int Looper::removeFd(int fd) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700500 AutoMutex _l(mLock);
501 const auto& it = mSequenceNumberByFd.find(fd);
502 if (it == mSequenceNumberByFd.end()) {
503 return 0;
504 }
505 return removeSequenceNumberLocked(it->second);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700506}
507
Steven Moreland34a09862024-01-20 00:20:17 +0000508int Looper::repoll(int fd) {
509 AutoMutex _l(mLock);
510 const auto& it = mSequenceNumberByFd.find(fd);
511 if (it == mSequenceNumberByFd.end()) {
512 return 0;
513 }
514
515 const auto& request_it = mRequests.find(it->second);
516 if (request_it == mRequests.end()) {
517 return 0;
518 }
519 const auto& [seq, request] = *request_it;
520
521 LOG_ALWAYS_FATAL_IF(
522 fd != request.fd,
523 "Looper has inconsistent data structure. When looking up FD %d found FD %d.", fd,
524 request_it->second.fd);
525
526 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
527 if (epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem) == -1) return 0;
528
529 return 1; // success
530}
531
Prabir Pradhan729057a2021-08-12 12:36:31 -0700532int Looper::removeSequenceNumberLocked(SequenceNumber seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700533#if DEBUG_CALLBACKS
Kai Sky862f0492023-11-24 14:20:20 +0000534 ALOGD("%p ~ removeFd - seq=%" PRIu64, this, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700535#endif
536
Prabir Pradhan729057a2021-08-12 12:36:31 -0700537 const auto& request_it = mRequests.find(seq);
538 if (request_it == mRequests.end()) {
539 return 0;
540 }
541 const int fd = request_it->second.fd;
Jeff Brown7901eb22010-09-13 23:17:30 -0700542
Prabir Pradhan729057a2021-08-12 12:36:31 -0700543 // Always remove the FD from the request map even if an error occurs while
544 // updating the epoll set so that we avoid accidentally leaking callbacks.
545 mRequests.erase(request_it);
546 mSequenceNumberByFd.erase(fd);
547
548 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
549 if (epollResult < 0) {
550 if (errno == EBADF || errno == ENOENT) {
551 // Tolerate EBADF or ENOENT because it means that the file descriptor was closed
552 // before its callback was unregistered. This error may occur naturally when a
553 // callback has the side-effect of closing the file descriptor before returning and
554 // unregistering itself.
555 //
556 // Unfortunately due to kernel limitations we need to rebuild the epoll
557 // set from scratch because it may contain an old file handle that we are
558 // now unable to remove since its file descriptor is no longer valid.
559 // No such problem would have occurred if we were using the poll system
560 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700561#if DEBUG_CALLBACKS
Prabir Pradhan729057a2021-08-12 12:36:31 -0700562 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
563 "being closed: %s",
564 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700565#endif
Prabir Pradhan729057a2021-08-12 12:36:31 -0700566 scheduleEpollRebuildLocked();
567 } else {
568 // Some other error occurred. This is really weird because it means
569 // our list of callbacks got out of sync with the epoll set somehow.
570 // We defensively rebuild the epoll set to avoid getting spurious
571 // notifications with nowhere to go.
572 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
573 scheduleEpollRebuildLocked();
574 return -1;
Jeff Brown7901eb22010-09-13 23:17:30 -0700575 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700576 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700577 return 1;
578}
579
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800580void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700581 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
582 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800583}
584
585void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
586 const Message& message) {
587 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
588 sendMessageAtTime(now + uptimeDelay, handler, message);
589}
590
591void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
592 const Message& message) {
593#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700594 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800595 this, uptime, handler.get(), message.what);
596#endif
597
598 size_t i = 0;
599 { // acquire lock
600 AutoMutex _l(mLock);
601
602 size_t messageCount = mMessageEnvelopes.size();
603 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
604 i += 1;
605 }
606
607 MessageEnvelope messageEnvelope(uptime, handler, message);
608 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
609
610 // Optimization: If the Looper is currently sending a message, then we can skip
611 // the call to wake() because the next thing the Looper will do after processing
612 // messages is to decide when the next wakeup time should be. In fact, it does
613 // not even matter whether this code is running on the Looper thread.
614 if (mSendingMessage) {
615 return;
616 }
617 } // release lock
618
619 // Wake the poll loop only when we enqueue a new message at the head.
620 if (i == 0) {
621 wake();
622 }
623}
624
625void Looper::removeMessages(const sp<MessageHandler>& handler) {
626#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000627 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800628#endif
629
630 { // acquire lock
631 AutoMutex _l(mLock);
632
633 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
634 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
635 if (messageEnvelope.handler == handler) {
636 mMessageEnvelopes.removeAt(i);
637 }
638 }
639 } // release lock
640}
641
642void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
643#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000644 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800645#endif
646
647 { // acquire lock
648 AutoMutex _l(mLock);
649
650 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
651 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
652 if (messageEnvelope.handler == handler
653 && messageEnvelope.message.what == what) {
654 mMessageEnvelopes.removeAt(i);
655 }
656 }
657 } // release lock
658}
659
Jeff Brown27e57212015-02-26 14:16:30 -0800660bool Looper::isPolling() const {
661 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700662}
663
Prabir Pradhan729057a2021-08-12 12:36:31 -0700664uint32_t Looper::Request::getEpollEvents() const {
665 uint32_t epollEvents = 0;
Jeff Browne7d54f82015-03-12 19:32:39 -0700666 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
667 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700668 return epollEvents;
Jeff Browne7d54f82015-03-12 19:32:39 -0700669}
670
Colin Cross17b5b822016-09-15 18:15:37 -0700671MessageHandler::~MessageHandler() { }
672
673LooperCallback::~LooperCallback() { }
674
Jeff Brown7901eb22010-09-13 23:17:30 -0700675} // namespace android