blob: 1a3f34bed1647d99a4f30c738851e5bc41e3af95 [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
Steven Morelanda06e68c2021-04-27 00:09:23 +0000120 Looper* looper = (Looper*)pthread_getspecific(gTLSKey);
121 return sp<Looper>::fromExisting(looper);
Jeff Brown7901eb22010-09-13 23:17:30 -0700122}
123
124sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800125 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700126 sp<Looper> looper = Looper::getForThread();
Yi Konge1731a42018-07-16 18:11:34 -0700127 if (looper == nullptr) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000128 looper = sp<Looper>::make(allowNonCallbacks);
Jeff Brown7901eb22010-09-13 23:17:30 -0700129 Looper::setForThread(looper);
130 }
131 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000132 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800133 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700134 }
135 return looper;
136}
137
138bool Looper::getAllowNonCallbacks() const {
139 return mAllowNonCallbacks;
140}
141
Jeff Browne7d54f82015-03-12 19:32:39 -0700142void Looper::rebuildEpollLocked() {
143 // Close old epoll instance if we have one.
144 if (mEpollFd >= 0) {
145#if DEBUG_CALLBACKS
146 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
147#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700148 mEpollFd.reset();
Jeff Browne7d54f82015-03-12 19:32:39 -0700149 }
150
Prabir Pradhan729057a2021-08-12 12:36:31 -0700151 // Allocate the new epoll instance and register the WakeEventFd.
Nick Kralevich0a8b4d12018-12-17 09:35:12 -0800152 mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700153 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700154
Prabir Pradhan729057a2021-08-12 12:36:31 -0700155 epoll_event wakeEvent = createEpollEvent(EPOLLIN, WAKE_EVENT_FD_SEQ);
156 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &wakeEvent);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700157 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
158 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700159
Prabir Pradhan729057a2021-08-12 12:36:31 -0700160 for (const auto& [seq, request] : mRequests) {
161 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
Jeff Browne7d54f82015-03-12 19:32:39 -0700162
Josh Gao2d08ae52018-07-18 17:26:24 -0700163 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
Jeff Browne7d54f82015-03-12 19:32:39 -0700164 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700165 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
166 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700167 }
168 }
169}
170
171void Looper::scheduleEpollRebuildLocked() {
172 if (!mEpollRebuildRequired) {
173#if DEBUG_CALLBACKS
174 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
175#endif
176 mEpollRebuildRequired = true;
177 wake();
178 }
179}
180
Jeff Brown7901eb22010-09-13 23:17:30 -0700181int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
182 int result = 0;
183 for (;;) {
184 while (mResponseIndex < mResponses.size()) {
185 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700186 int ident = response.request.ident;
187 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800188 int fd = response.request.fd;
189 int events = response.events;
190 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700191#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000192 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800193 "fd=%d, events=0x%x, data=%p",
194 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700195#endif
Yi Konge1731a42018-07-16 18:11:34 -0700196 if (outFd != nullptr) *outFd = fd;
197 if (outEvents != nullptr) *outEvents = events;
198 if (outData != nullptr) *outData = data;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800199 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700200 }
201 }
202
203 if (result != 0) {
204#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000205 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700206#endif
Yi Konge1731a42018-07-16 18:11:34 -0700207 if (outFd != nullptr) *outFd = 0;
208 if (outEvents != nullptr) *outEvents = 0;
209 if (outData != nullptr) *outData = nullptr;
Jeff Brown7901eb22010-09-13 23:17:30 -0700210 return result;
211 }
212
213 result = pollInner(timeoutMillis);
214 }
215}
216
217int Looper::pollInner(int timeoutMillis) {
218#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000219 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700220#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700221
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800222 // Adjust the timeout based on when the next message is due.
223 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
224 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700225 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
226 if (messageTimeoutMillis >= 0
227 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
228 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800229 }
230#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700231 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800232 this, mNextMessageUptime - now, timeoutMillis);
233#endif
234 }
235
236 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800237 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700238 mResponses.clear();
239 mResponseIndex = 0;
240
Dianne Hackborn19159f92013-05-06 14:25:20 -0700241 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800242 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700243
Jeff Brown7901eb22010-09-13 23:17:30 -0700244 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
Josh Gao2d08ae52018-07-18 17:26:24 -0700245 int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700246
Dianne Hackborn19159f92013-05-06 14:25:20 -0700247 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800248 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700249
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800250 // Acquire lock.
251 mLock.lock();
252
Jeff Browne7d54f82015-03-12 19:32:39 -0700253 // Rebuild epoll set if needed.
254 if (mEpollRebuildRequired) {
255 mEpollRebuildRequired = false;
256 rebuildEpollLocked();
257 goto Done;
258 }
259
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800260 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700261 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700262 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700263 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700264 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700265 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800266 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700267 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700268 }
269
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800270 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700271 if (eventCount == 0) {
272#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000273 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700274#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800275 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700276 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700277 }
278
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800279 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700280#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000281 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700282#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700283
Jeff Brown9da18102010-09-17 17:01:23 -0700284 for (int i = 0; i < eventCount; i++) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700285 const SequenceNumber seq = eventItems[i].data.u64;
Jeff Brown9da18102010-09-17 17:01:23 -0700286 uint32_t epollEvents = eventItems[i].events;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700287 if (seq == WAKE_EVENT_FD_SEQ) {
Jeff Brown9da18102010-09-17 17:01:23 -0700288 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700289 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700290 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700291 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700292 }
293 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700294 const auto& request_it = mRequests.find(seq);
295 if (request_it != mRequests.end()) {
296 const auto& request = request_it->second;
Jeff Brown9da18102010-09-17 17:01:23 -0700297 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800298 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
299 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
300 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
301 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700302 mResponses.push({.seq = seq, .events = events, .request = request});
Jeff Brown9da18102010-09-17 17:01:23 -0700303 } else {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700304 ALOGW("Ignoring unexpected epoll events 0x%x for sequence number %" PRIu64
305 " that is no longer registered.",
306 epollEvents, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700307 }
308 }
309 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700310Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700311
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800312 // Invoke pending message callbacks.
313 mNextMessageUptime = LLONG_MAX;
314 while (mMessageEnvelopes.size() != 0) {
315 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
316 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
317 if (messageEnvelope.uptime <= now) {
318 // Remove the envelope from the list.
319 // We keep a strong reference to the handler until the call to handleMessage
320 // finishes. Then we drop it so that the handler can be deleted *before*
321 // we reacquire our lock.
322 { // obtain handler
323 sp<MessageHandler> handler = messageEnvelope.handler;
324 Message message = messageEnvelope.message;
325 mMessageEnvelopes.removeAt(0);
326 mSendingMessage = true;
327 mLock.unlock();
328
329#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000330 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800331 this, handler.get(), message.what);
332#endif
333 handler->handleMessage(message);
334 } // release handler
335
336 mLock.lock();
337 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800338 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800339 } else {
340 // The last message left at the head of the queue determines the next wakeup time.
341 mNextMessageUptime = messageEnvelope.uptime;
342 break;
343 }
344 }
345
346 // Release lock.
347 mLock.unlock();
348
349 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700350 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700351 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800352 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800353 int fd = response.request.fd;
354 int events = response.events;
355 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700356#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000357 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700358 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700359#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700360 // Invoke the callback. Note that the file descriptor may be closed by
361 // the callback (and potentially even reused) before the function returns so
362 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700363 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700364 if (callbackResult == 0) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700365 AutoMutex _l(mLock);
366 removeSequenceNumberLocked(response.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700367 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700368
Jeff Browndd1b0372012-05-31 16:15:35 -0700369 // Clear the callback reference in the response structure promptly because we
370 // will not clear the response vector itself until the next poll.
371 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800372 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700373 }
374 }
375 return result;
376}
377
378int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
379 if (timeoutMillis <= 0) {
380 int result;
381 do {
382 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800383 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700384 return result;
385 } else {
386 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
387 + milliseconds_to_nanoseconds(timeoutMillis);
388
389 for (;;) {
390 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800391 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700392 return result;
393 }
394
Jeff Brown43550ee2011-03-17 01:34:19 -0700395 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
396 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
397 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800398 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700399 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700400 }
401 }
402}
403
404void Looper::wake() {
405#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000406 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700407#endif
408
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700409 uint64_t inc = 1;
Josh Gao2d08ae52018-07-18 17:26:24 -0700410 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700411 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700412 if (errno != EAGAIN) {
Elliott Hughesfd121602019-04-01 12:22:55 -0700413 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
414 mWakeEventFd.get(), nWrite, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700415 }
416 }
417}
418
Jeff Brown8d15c742010-10-05 15:35:37 -0700419void Looper::awoken() {
420#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000421 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700422#endif
423
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700424 uint64_t counter;
Josh Gao2d08ae52018-07-18 17:26:24 -0700425 TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700426}
427
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800428int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000429 sp<SimpleLooperCallback> looperCallback;
430 if (callback) {
431 looperCallback = sp<SimpleLooperCallback>::make(callback);
432 }
433 return addFd(fd, ident, events, looperCallback, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700434}
435
436int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700437#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000438 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700439 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700440#endif
441
Jeff Browndd1b0372012-05-31 16:15:35 -0700442 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700443 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000444 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700445 return -1;
446 }
447
448 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700449 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700450 return -1;
451 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700452 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800453 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700454 }
455
456 { // acquire lock
457 AutoMutex _l(mLock);
Prabir Pradhan729057a2021-08-12 12:36:31 -0700458 // There is a sequence number reserved for the WakeEventFd.
459 if (mNextRequestSeq == WAKE_EVENT_FD_SEQ) mNextRequestSeq++;
460 const SequenceNumber seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700461
462 Request request;
463 request.fd = fd;
464 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700465 request.events = events;
Jeff Brown7901eb22010-09-13 23:17:30 -0700466 request.callback = callback;
467 request.data = data;
468
Prabir Pradhan729057a2021-08-12 12:36:31 -0700469 epoll_event eventItem = createEpollEvent(request.getEpollEvents(), seq);
470 auto seq_it = mSequenceNumberByFd.find(fd);
471 if (seq_it == mSequenceNumberByFd.end()) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700472 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700473 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700474 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700475 return -1;
476 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700477 mRequests.emplace(seq, request);
478 mSequenceNumberByFd.emplace(fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700479 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700480 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700481 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700482 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700483 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700484 // closed before its callback was unregistered and meanwhile a new
485 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700486 // being registered for the first time. This error may occur naturally
487 // when a callback has the side-effect of closing the file descriptor
488 // before returning and unregistering itself. Callback sequence number
489 // checks further ensure that the race is benign.
490 //
491 // Unfortunately due to kernel limitations we need to rebuild the epoll
492 // set from scratch because it may contain an old file handle that we are
493 // now unable to remove since its file descriptor is no longer valid.
494 // No such problem would have occurred if we were using the poll system
Prabir Pradhan729057a2021-08-12 12:36:31 -0700495 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700496#if DEBUG_CALLBACKS
497 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700498 "being recycled, falling back on EPOLL_CTL_ADD: %s",
499 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700500#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700501 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700502 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700503 ALOGE("Error modifying or adding epoll events for fd %d: %s",
504 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700505 return -1;
506 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700507 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700508 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700509 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700510 return -1;
511 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700512 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700513 const SequenceNumber oldSeq = seq_it->second;
514 mRequests.erase(oldSeq);
515 mRequests.emplace(seq, request);
516 seq_it->second = seq;
Jeff Brown7901eb22010-09-13 23:17:30 -0700517 }
518 } // release lock
519 return 1;
520}
521
522int Looper::removeFd(int fd) {
Prabir Pradhan729057a2021-08-12 12:36:31 -0700523 AutoMutex _l(mLock);
524 const auto& it = mSequenceNumberByFd.find(fd);
525 if (it == mSequenceNumberByFd.end()) {
526 return 0;
527 }
528 return removeSequenceNumberLocked(it->second);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700529}
530
Prabir Pradhan729057a2021-08-12 12:36:31 -0700531int Looper::removeSequenceNumberLocked(SequenceNumber seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700532#if DEBUG_CALLBACKS
Prabir Pradhan729057a2021-08-12 12:36:31 -0700533 ALOGD("%p ~ removeFd - fd=%d, seq=%u", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700534#endif
535
Prabir Pradhan729057a2021-08-12 12:36:31 -0700536 const auto& request_it = mRequests.find(seq);
537 if (request_it == mRequests.end()) {
538 return 0;
539 }
540 const int fd = request_it->second.fd;
Jeff Brown7901eb22010-09-13 23:17:30 -0700541
Prabir Pradhan729057a2021-08-12 12:36:31 -0700542 // Always remove the FD from the request map even if an error occurs while
543 // updating the epoll set so that we avoid accidentally leaking callbacks.
544 mRequests.erase(request_it);
545 mSequenceNumberByFd.erase(fd);
546
547 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
548 if (epollResult < 0) {
549 if (errno == EBADF || errno == ENOENT) {
550 // Tolerate EBADF or ENOENT because it means that the file descriptor was closed
551 // before its callback was unregistered. This error may occur naturally when a
552 // callback has the side-effect of closing the file descriptor before returning and
553 // unregistering itself.
554 //
555 // Unfortunately due to kernel limitations we need to rebuild the epoll
556 // set from scratch because it may contain an old file handle that we are
557 // now unable to remove since its file descriptor is no longer valid.
558 // No such problem would have occurred if we were using the poll system
559 // call instead, but that approach carries other disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700560#if DEBUG_CALLBACKS
Prabir Pradhan729057a2021-08-12 12:36:31 -0700561 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
562 "being closed: %s",
563 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700564#endif
Prabir Pradhan729057a2021-08-12 12:36:31 -0700565 scheduleEpollRebuildLocked();
566 } else {
567 // Some other error occurred. This is really weird because it means
568 // our list of callbacks got out of sync with the epoll set somehow.
569 // We defensively rebuild the epoll set to avoid getting spurious
570 // notifications with nowhere to go.
571 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
572 scheduleEpollRebuildLocked();
573 return -1;
Jeff Brown7901eb22010-09-13 23:17:30 -0700574 }
Prabir Pradhan729057a2021-08-12 12:36:31 -0700575 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700576 return 1;
577}
578
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800579void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700580 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
581 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800582}
583
584void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
585 const Message& message) {
586 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
587 sendMessageAtTime(now + uptimeDelay, handler, message);
588}
589
590void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
591 const Message& message) {
592#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700593 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800594 this, uptime, handler.get(), message.what);
595#endif
596
597 size_t i = 0;
598 { // acquire lock
599 AutoMutex _l(mLock);
600
601 size_t messageCount = mMessageEnvelopes.size();
602 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
603 i += 1;
604 }
605
606 MessageEnvelope messageEnvelope(uptime, handler, message);
607 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
608
609 // Optimization: If the Looper is currently sending a message, then we can skip
610 // the call to wake() because the next thing the Looper will do after processing
611 // messages is to decide when the next wakeup time should be. In fact, it does
612 // not even matter whether this code is running on the Looper thread.
613 if (mSendingMessage) {
614 return;
615 }
616 } // release lock
617
618 // Wake the poll loop only when we enqueue a new message at the head.
619 if (i == 0) {
620 wake();
621 }
622}
623
624void Looper::removeMessages(const sp<MessageHandler>& handler) {
625#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000626 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800627#endif
628
629 { // acquire lock
630 AutoMutex _l(mLock);
631
632 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
633 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
634 if (messageEnvelope.handler == handler) {
635 mMessageEnvelopes.removeAt(i);
636 }
637 }
638 } // release lock
639}
640
641void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
642#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000643 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800644#endif
645
646 { // acquire lock
647 AutoMutex _l(mLock);
648
649 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
650 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
651 if (messageEnvelope.handler == handler
652 && messageEnvelope.message.what == what) {
653 mMessageEnvelopes.removeAt(i);
654 }
655 }
656 } // release lock
657}
658
Jeff Brown27e57212015-02-26 14:16:30 -0800659bool Looper::isPolling() const {
660 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700661}
662
Prabir Pradhan729057a2021-08-12 12:36:31 -0700663uint32_t Looper::Request::getEpollEvents() const {
664 uint32_t epollEvents = 0;
Jeff Browne7d54f82015-03-12 19:32:39 -0700665 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
666 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
Prabir Pradhan729057a2021-08-12 12:36:31 -0700667 return epollEvents;
Jeff Browne7d54f82015-03-12 19:32:39 -0700668}
669
Colin Cross17b5b822016-09-15 18:15:37 -0700670MessageHandler::~MessageHandler() { }
671
672LooperCallback::~LooperCallback() { }
673
Jeff Brown7901eb22010-09-13 23:17:30 -0700674} // namespace android