blob: 4b01e5c2b8ad7f54ab4916c1d762a5506a994bf0 [file] [log] [blame]
Jeff Brown7901eb22010-09-13 23:17:30 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// A looper implementation based on epoll().
5//
6#define LOG_TAG "Looper"
7
8//#define LOG_NDEBUG 0
9
10// Debugs poll and wake interactions.
11#define DEBUG_POLL_AND_WAKE 0
12
13// Debugs callback registration and invocation.
14#define DEBUG_CALLBACKS 0
15
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070016#include <utils/Looper.h>
Alessio Balsini14062072019-05-11 14:29:28 +010017
Mathias Agopian22dbf392017-02-28 15:06:51 -080018#include <sys/eventfd.h>
Alessio Balsini14062072019-05-11 14:29:28 +010019#include <cinttypes>
Jeff Brown7901eb22010-09-13 23:17:30 -070020
21namespace android {
22
Jeff Brown3e2e38b2011-03-02 14:41:58 -080023// --- WeakMessageHandler ---
24
25WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
26 mHandler(handler) {
27}
28
Jeff Browndd1b0372012-05-31 16:15:35 -070029WeakMessageHandler::~WeakMessageHandler() {
30}
31
Jeff Brown3e2e38b2011-03-02 14:41:58 -080032void WeakMessageHandler::handleMessage(const Message& message) {
33 sp<MessageHandler> handler = mHandler.promote();
Yi Konge1731a42018-07-16 18:11:34 -070034 if (handler != nullptr) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -080035 handler->handleMessage(message);
36 }
37}
38
39
Jeff Browndd1b0372012-05-31 16:15:35 -070040// --- SimpleLooperCallback ---
41
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080042SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070043 mCallback(callback) {
44}
45
46SimpleLooperCallback::~SimpleLooperCallback() {
47}
48
49int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
50 return mCallback(fd, events, data);
51}
52
53
Jeff Brown3e2e38b2011-03-02 14:41:58 -080054// --- Looper ---
55
Jeff Brown7901eb22010-09-13 23:17:30 -070056// Maximum number of file descriptors for which to retrieve poll events each iteration.
57static const int EPOLL_MAX_EVENTS = 16;
58
Jeff Brownd1805182010-09-21 15:11:18 -070059static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
60static pthread_key_t gTLSKey = 0;
61
Josh Gao2d08ae52018-07-18 17:26:24 -070062Looper::Looper(bool allowNonCallbacks)
63 : mAllowNonCallbacks(allowNonCallbacks),
64 mSendingMessage(false),
65 mPolling(false),
66 mEpollRebuildRequired(false),
67 mNextRequestSeq(0),
68 mResponseIndex(0),
69 mNextMessageUptime(LLONG_MAX) {
70 mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
71 LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070072
Jeff Browne7d54f82015-03-12 19:32:39 -070073 AutoMutex _l(mLock);
74 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070075}
76
77Looper::~Looper() {
Jeff Brown7901eb22010-09-13 23:17:30 -070078}
79
Jeff Brownd1805182010-09-21 15:11:18 -070080void Looper::initTLSKey() {
Elliott Hughesfd121602019-04-01 12:22:55 -070081 int error = pthread_key_create(&gTLSKey, threadDestructor);
82 LOG_ALWAYS_FATAL_IF(error != 0, "Could not allocate TLS key: %s", strerror(error));
Jeff Brownd1805182010-09-21 15:11:18 -070083}
84
Jeff Brown7901eb22010-09-13 23:17:30 -070085void Looper::threadDestructor(void *st) {
86 Looper* const self = static_cast<Looper*>(st);
Yi Konge1731a42018-07-16 18:11:34 -070087 if (self != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070088 self->decStrong((void*)threadDestructor);
89 }
90}
91
92void Looper::setForThread(const sp<Looper>& looper) {
93 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
94
Yi Konge1731a42018-07-16 18:11:34 -070095 if (looper != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070096 looper->incStrong((void*)threadDestructor);
97 }
98
Jeff Brownd1805182010-09-21 15:11:18 -070099 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700100
Yi Konge1731a42018-07-16 18:11:34 -0700101 if (old != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700102 old->decStrong((void*)threadDestructor);
103 }
104}
105
106sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700107 int result = pthread_once(& gTLSOnce, initTLSKey);
108 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700109
Steven Morelanda06e68c2021-04-27 00:09:23 +0000110 Looper* looper = (Looper*)pthread_getspecific(gTLSKey);
111 return sp<Looper>::fromExisting(looper);
Jeff Brown7901eb22010-09-13 23:17:30 -0700112}
113
114sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800115 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700116 sp<Looper> looper = Looper::getForThread();
Yi Konge1731a42018-07-16 18:11:34 -0700117 if (looper == nullptr) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000118 looper = sp<Looper>::make(allowNonCallbacks);
Jeff Brown7901eb22010-09-13 23:17:30 -0700119 Looper::setForThread(looper);
120 }
121 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000122 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800123 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700124 }
125 return looper;
126}
127
128bool Looper::getAllowNonCallbacks() const {
129 return mAllowNonCallbacks;
130}
131
Jeff Browne7d54f82015-03-12 19:32:39 -0700132void Looper::rebuildEpollLocked() {
133 // Close old epoll instance if we have one.
134 if (mEpollFd >= 0) {
135#if DEBUG_CALLBACKS
136 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
137#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700138 mEpollFd.reset();
Jeff Browne7d54f82015-03-12 19:32:39 -0700139 }
140
141 // Allocate the new epoll instance and register the wake pipe.
Nick Kralevich0a8b4d12018-12-17 09:35:12 -0800142 mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700143 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700144
145 struct epoll_event eventItem;
146 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
147 eventItem.events = EPOLLIN;
Josh Gao2d08ae52018-07-18 17:26:24 -0700148 eventItem.data.fd = mWakeEventFd.get();
149 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &eventItem);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700150 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
151 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700152
153 for (size_t i = 0; i < mRequests.size(); i++) {
154 const Request& request = mRequests.valueAt(i);
155 struct epoll_event eventItem;
156 request.initEventItem(&eventItem);
157
Josh Gao2d08ae52018-07-18 17:26:24 -0700158 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
Jeff Browne7d54f82015-03-12 19:32:39 -0700159 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700160 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
161 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700162 }
163 }
164}
165
166void Looper::scheduleEpollRebuildLocked() {
167 if (!mEpollRebuildRequired) {
168#if DEBUG_CALLBACKS
169 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
170#endif
171 mEpollRebuildRequired = true;
172 wake();
173 }
174}
175
Jeff Brown7901eb22010-09-13 23:17:30 -0700176int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
177 int result = 0;
178 for (;;) {
179 while (mResponseIndex < mResponses.size()) {
180 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700181 int ident = response.request.ident;
182 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800183 int fd = response.request.fd;
184 int events = response.events;
185 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700186#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000187 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800188 "fd=%d, events=0x%x, data=%p",
189 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700190#endif
Yi Konge1731a42018-07-16 18:11:34 -0700191 if (outFd != nullptr) *outFd = fd;
192 if (outEvents != nullptr) *outEvents = events;
193 if (outData != nullptr) *outData = data;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800194 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700195 }
196 }
197
198 if (result != 0) {
199#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000200 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700201#endif
Yi Konge1731a42018-07-16 18:11:34 -0700202 if (outFd != nullptr) *outFd = 0;
203 if (outEvents != nullptr) *outEvents = 0;
204 if (outData != nullptr) *outData = nullptr;
Jeff Brown7901eb22010-09-13 23:17:30 -0700205 return result;
206 }
207
208 result = pollInner(timeoutMillis);
209 }
210}
211
212int Looper::pollInner(int timeoutMillis) {
213#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000214 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700215#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700216
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800217 // Adjust the timeout based on when the next message is due.
218 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
219 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700220 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
221 if (messageTimeoutMillis >= 0
222 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
223 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800224 }
225#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700226 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800227 this, mNextMessageUptime - now, timeoutMillis);
228#endif
229 }
230
231 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800232 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700233 mResponses.clear();
234 mResponseIndex = 0;
235
Dianne Hackborn19159f92013-05-06 14:25:20 -0700236 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800237 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700238
Jeff Brown7901eb22010-09-13 23:17:30 -0700239 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
Josh Gao2d08ae52018-07-18 17:26:24 -0700240 int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700241
Dianne Hackborn19159f92013-05-06 14:25:20 -0700242 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800243 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700244
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800245 // Acquire lock.
246 mLock.lock();
247
Jeff Browne7d54f82015-03-12 19:32:39 -0700248 // Rebuild epoll set if needed.
249 if (mEpollRebuildRequired) {
250 mEpollRebuildRequired = false;
251 rebuildEpollLocked();
252 goto Done;
253 }
254
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800255 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700256 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700257 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700258 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700259 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700260 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800261 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700262 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700263 }
264
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800265 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700266 if (eventCount == 0) {
267#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000268 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700269#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800270 result = POLL_TIMEOUT;
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 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700275#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000276 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700277#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700278
Jeff Brown9da18102010-09-17 17:01:23 -0700279 for (int i = 0; i < eventCount; i++) {
280 int fd = eventItems[i].data.fd;
281 uint32_t epollEvents = eventItems[i].events;
Josh Gao2d08ae52018-07-18 17:26:24 -0700282 if (fd == mWakeEventFd.get()) {
Jeff Brown9da18102010-09-17 17:01:23 -0700283 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700284 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700285 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700286 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700287 }
288 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700289 ssize_t requestIndex = mRequests.indexOfKey(fd);
290 if (requestIndex >= 0) {
291 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800292 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
293 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
294 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
295 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700296 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700297 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000298 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700299 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700300 }
301 }
302 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700303Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700304
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800305 // Invoke pending message callbacks.
306 mNextMessageUptime = LLONG_MAX;
307 while (mMessageEnvelopes.size() != 0) {
308 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
309 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
310 if (messageEnvelope.uptime <= now) {
311 // Remove the envelope from the list.
312 // We keep a strong reference to the handler until the call to handleMessage
313 // finishes. Then we drop it so that the handler can be deleted *before*
314 // we reacquire our lock.
315 { // obtain handler
316 sp<MessageHandler> handler = messageEnvelope.handler;
317 Message message = messageEnvelope.message;
318 mMessageEnvelopes.removeAt(0);
319 mSendingMessage = true;
320 mLock.unlock();
321
322#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000323 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800324 this, handler.get(), message.what);
325#endif
326 handler->handleMessage(message);
327 } // release handler
328
329 mLock.lock();
330 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800331 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800332 } else {
333 // The last message left at the head of the queue determines the next wakeup time.
334 mNextMessageUptime = messageEnvelope.uptime;
335 break;
336 }
337 }
338
339 // Release lock.
340 mLock.unlock();
341
342 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700343 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700344 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800345 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800346 int fd = response.request.fd;
347 int events = response.events;
348 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700349#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000350 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700351 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700352#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700353 // Invoke the callback. Note that the file descriptor may be closed by
354 // the callback (and potentially even reused) before the function returns so
355 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700356 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700357 if (callbackResult == 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700358 removeFd(fd, response.request.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700359 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700360
Jeff Browndd1b0372012-05-31 16:15:35 -0700361 // Clear the callback reference in the response structure promptly because we
362 // will not clear the response vector itself until the next poll.
363 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800364 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700365 }
366 }
367 return result;
368}
369
370int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
371 if (timeoutMillis <= 0) {
372 int result;
373 do {
374 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800375 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700376 return result;
377 } else {
378 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
379 + milliseconds_to_nanoseconds(timeoutMillis);
380
381 for (;;) {
382 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800383 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700384 return result;
385 }
386
Jeff Brown43550ee2011-03-17 01:34:19 -0700387 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
388 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
389 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800390 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700391 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700392 }
393 }
394}
395
396void Looper::wake() {
397#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000398 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700399#endif
400
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700401 uint64_t inc = 1;
Josh Gao2d08ae52018-07-18 17:26:24 -0700402 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700403 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700404 if (errno != EAGAIN) {
Elliott Hughesfd121602019-04-01 12:22:55 -0700405 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d (returned %zd): %s",
406 mWakeEventFd.get(), nWrite, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700407 }
408 }
409}
410
Jeff Brown8d15c742010-10-05 15:35:37 -0700411void Looper::awoken() {
412#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000413 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700414#endif
415
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700416 uint64_t counter;
Josh Gao2d08ae52018-07-18 17:26:24 -0700417 TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700418}
419
420void Looper::pushResponse(int events, const Request& request) {
421 Response response;
422 response.events = events;
423 response.request = request;
424 mResponses.push(response);
425}
426
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800427int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Steven Morelanda06e68c2021-04-27 00:09:23 +0000428 sp<SimpleLooperCallback> looperCallback;
429 if (callback) {
430 looperCallback = sp<SimpleLooperCallback>::make(callback);
431 }
432 return addFd(fd, ident, events, looperCallback, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700433}
434
435int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700436#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000437 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700438 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700439#endif
440
Jeff Browndd1b0372012-05-31 16:15:35 -0700441 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700442 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000443 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700444 return -1;
445 }
446
447 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700448 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700449 return -1;
450 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700451 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800452 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700453 }
454
455 { // acquire lock
456 AutoMutex _l(mLock);
457
458 Request request;
459 request.fd = fd;
460 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700461 request.events = events;
462 request.seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700463 request.callback = callback;
464 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700465 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700466
467 struct epoll_event eventItem;
Jeff Browne7d54f82015-03-12 19:32:39 -0700468 request.initEventItem(&eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700469
470 ssize_t requestIndex = mRequests.indexOfKey(fd);
471 if (requestIndex < 0) {
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 }
477 mRequests.add(fd, request);
478 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700479 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700480 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700481 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700482 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700483 // closed before its callback was unregistered and meanwhile a new
484 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700485 // being registered for the first time. This error may occur naturally
486 // when a callback has the side-effect of closing the file descriptor
487 // before returning and unregistering itself. Callback sequence number
488 // checks further ensure that the race is benign.
489 //
490 // Unfortunately due to kernel limitations we need to rebuild the epoll
491 // set from scratch because it may contain an old file handle that we are
492 // now unable to remove since its file descriptor is no longer valid.
493 // No such problem would have occurred if we were using the poll system
494 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700495#if DEBUG_CALLBACKS
496 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700497 "being recycled, falling back on EPOLL_CTL_ADD: %s",
498 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700499#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700500 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700501 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700502 ALOGE("Error modifying or adding epoll events for fd %d: %s",
503 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700504 return -1;
505 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700506 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700507 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700508 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700509 return -1;
510 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700511 }
512 mRequests.replaceValueAt(requestIndex, request);
513 }
514 } // release lock
515 return 1;
516}
517
518int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700519 return removeFd(fd, -1);
520}
521
522int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700523#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700524 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700525#endif
526
527 { // acquire lock
528 AutoMutex _l(mLock);
529 ssize_t requestIndex = mRequests.indexOfKey(fd);
530 if (requestIndex < 0) {
531 return 0;
532 }
533
Jeff Brown7a0310e2015-03-10 18:31:12 -0700534 // Check the sequence number if one was given.
535 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
536#if DEBUG_CALLBACKS
537 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
538 this, mRequests.valueAt(requestIndex).seq);
539#endif
540 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700541 }
542
Jeff Brown7a0310e2015-03-10 18:31:12 -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.
Jeff Brown7901eb22010-09-13 23:17:30 -0700545 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700546
Josh Gao2d08ae52018-07-18 17:26:24 -0700547 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700548 if (epollResult < 0) {
549 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700550 // Tolerate EBADF or ENOENT when the sequence number is known because it
Jeff Brown7a0310e2015-03-10 18:31:12 -0700551 // means that the file descriptor was closed before its callback was
Jeff Browne7d54f82015-03-12 19:32:39 -0700552 // unregistered. This error may occur naturally when a callback has the
553 // 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 others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700561#if DEBUG_CALLBACKS
562 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700563 "being closed: %s", this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700564#endif
Jeff Browne7d54f82015-03-12 19:32:39 -0700565 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700566 } else {
Jeff Brown18a574f2015-05-29 17:40:25 -0700567 // 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.
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700571 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown18a574f2015-05-29 17:40:25 -0700572 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700573 return -1;
574 }
575 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700576 } // release lock
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
Jeff Browne7d54f82015-03-12 19:32:39 -0700664void Looper::Request::initEventItem(struct epoll_event* eventItem) const {
665 int epollEvents = 0;
666 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
667 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
668
669 memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
670 eventItem->events = epollEvents;
671 eventItem->data.fd = fd;
672}
673
Colin Cross17b5b822016-09-15 18:15:37 -0700674MessageHandler::~MessageHandler() { }
675
676LooperCallback::~LooperCallback() { }
677
Jeff Brown7901eb22010-09-13 23:17:30 -0700678} // namespace android