blob: b3f943d426199503bec885ea798217eb42efb3cf [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>
Mathias Agopian22dbf392017-02-28 15:06:51 -080017#include <sys/eventfd.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070018
19namespace android {
20
Jeff Brown3e2e38b2011-03-02 14:41:58 -080021// --- WeakMessageHandler ---
22
23WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
24 mHandler(handler) {
25}
26
Jeff Browndd1b0372012-05-31 16:15:35 -070027WeakMessageHandler::~WeakMessageHandler() {
28}
29
Jeff Brown3e2e38b2011-03-02 14:41:58 -080030void WeakMessageHandler::handleMessage(const Message& message) {
31 sp<MessageHandler> handler = mHandler.promote();
Yi Konge1731a42018-07-16 18:11:34 -070032 if (handler != nullptr) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -080033 handler->handleMessage(message);
34 }
35}
36
37
Jeff Browndd1b0372012-05-31 16:15:35 -070038// --- SimpleLooperCallback ---
39
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080040SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070041 mCallback(callback) {
42}
43
44SimpleLooperCallback::~SimpleLooperCallback() {
45}
46
47int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
48 return mCallback(fd, events, data);
49}
50
51
Jeff Brown3e2e38b2011-03-02 14:41:58 -080052// --- Looper ---
53
Jeff Brown7901eb22010-09-13 23:17:30 -070054// Maximum number of file descriptors for which to retrieve poll events each iteration.
55static const int EPOLL_MAX_EVENTS = 16;
56
Jeff Brownd1805182010-09-21 15:11:18 -070057static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
58static pthread_key_t gTLSKey = 0;
59
Josh Gao2d08ae52018-07-18 17:26:24 -070060Looper::Looper(bool allowNonCallbacks)
61 : mAllowNonCallbacks(allowNonCallbacks),
62 mSendingMessage(false),
63 mPolling(false),
64 mEpollRebuildRequired(false),
65 mNextRequestSeq(0),
66 mResponseIndex(0),
67 mNextMessageUptime(LLONG_MAX) {
68 mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
69 LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070070
Jeff Browne7d54f82015-03-12 19:32:39 -070071 AutoMutex _l(mLock);
72 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070073}
74
75Looper::~Looper() {
Jeff Brown7901eb22010-09-13 23:17:30 -070076}
77
Jeff Brownd1805182010-09-21 15:11:18 -070078void Looper::initTLSKey() {
79 int result = pthread_key_create(& gTLSKey, threadDestructor);
80 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
81}
82
Jeff Brown7901eb22010-09-13 23:17:30 -070083void Looper::threadDestructor(void *st) {
84 Looper* const self = static_cast<Looper*>(st);
Yi Konge1731a42018-07-16 18:11:34 -070085 if (self != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070086 self->decStrong((void*)threadDestructor);
87 }
88}
89
90void Looper::setForThread(const sp<Looper>& looper) {
91 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
92
Yi Konge1731a42018-07-16 18:11:34 -070093 if (looper != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070094 looper->incStrong((void*)threadDestructor);
95 }
96
Jeff Brownd1805182010-09-21 15:11:18 -070097 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -070098
Yi Konge1731a42018-07-16 18:11:34 -070099 if (old != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700100 old->decStrong((void*)threadDestructor);
101 }
102}
103
104sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700105 int result = pthread_once(& gTLSOnce, initTLSKey);
106 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700107
Jeff Brownd1805182010-09-21 15:11:18 -0700108 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700109}
110
111sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800112 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700113 sp<Looper> looper = Looper::getForThread();
Yi Konge1731a42018-07-16 18:11:34 -0700114 if (looper == nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700115 looper = new Looper(allowNonCallbacks);
116 Looper::setForThread(looper);
117 }
118 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000119 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800120 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700121 }
122 return looper;
123}
124
125bool Looper::getAllowNonCallbacks() const {
126 return mAllowNonCallbacks;
127}
128
Jeff Browne7d54f82015-03-12 19:32:39 -0700129void Looper::rebuildEpollLocked() {
130 // Close old epoll instance if we have one.
131 if (mEpollFd >= 0) {
132#if DEBUG_CALLBACKS
133 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
134#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700135 mEpollFd.reset();
Jeff Browne7d54f82015-03-12 19:32:39 -0700136 }
137
138 // Allocate the new epoll instance and register the wake pipe.
Nick Kralevich0a8b4d12018-12-17 09:35:12 -0800139 mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700140 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700141
142 struct epoll_event eventItem;
143 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
144 eventItem.events = EPOLLIN;
Josh Gao2d08ae52018-07-18 17:26:24 -0700145 eventItem.data.fd = mWakeEventFd.get();
146 int result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &eventItem);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700147 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
148 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700149
150 for (size_t i = 0; i < mRequests.size(); i++) {
151 const Request& request = mRequests.valueAt(i);
152 struct epoll_event eventItem;
153 request.initEventItem(&eventItem);
154
Josh Gao2d08ae52018-07-18 17:26:24 -0700155 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);
Jeff Browne7d54f82015-03-12 19:32:39 -0700156 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700157 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
158 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700159 }
160 }
161}
162
163void Looper::scheduleEpollRebuildLocked() {
164 if (!mEpollRebuildRequired) {
165#if DEBUG_CALLBACKS
166 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
167#endif
168 mEpollRebuildRequired = true;
169 wake();
170 }
171}
172
Jeff Brown7901eb22010-09-13 23:17:30 -0700173int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
174 int result = 0;
175 for (;;) {
176 while (mResponseIndex < mResponses.size()) {
177 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700178 int ident = response.request.ident;
179 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800180 int fd = response.request.fd;
181 int events = response.events;
182 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700183#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000184 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800185 "fd=%d, events=0x%x, data=%p",
186 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700187#endif
Yi Konge1731a42018-07-16 18:11:34 -0700188 if (outFd != nullptr) *outFd = fd;
189 if (outEvents != nullptr) *outEvents = events;
190 if (outData != nullptr) *outData = data;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800191 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700192 }
193 }
194
195 if (result != 0) {
196#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000197 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700198#endif
Yi Konge1731a42018-07-16 18:11:34 -0700199 if (outFd != nullptr) *outFd = 0;
200 if (outEvents != nullptr) *outEvents = 0;
201 if (outData != nullptr) *outData = nullptr;
Jeff Brown7901eb22010-09-13 23:17:30 -0700202 return result;
203 }
204
205 result = pollInner(timeoutMillis);
206 }
207}
208
209int Looper::pollInner(int timeoutMillis) {
210#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000211 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700212#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700213
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800214 // Adjust the timeout based on when the next message is due.
215 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
216 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700217 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
218 if (messageTimeoutMillis >= 0
219 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
220 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800221 }
222#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700223 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800224 this, mNextMessageUptime - now, timeoutMillis);
225#endif
226 }
227
228 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800229 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700230 mResponses.clear();
231 mResponseIndex = 0;
232
Dianne Hackborn19159f92013-05-06 14:25:20 -0700233 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800234 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700235
Jeff Brown7901eb22010-09-13 23:17:30 -0700236 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
Josh Gao2d08ae52018-07-18 17:26:24 -0700237 int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700238
Dianne Hackborn19159f92013-05-06 14:25:20 -0700239 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800240 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700241
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800242 // Acquire lock.
243 mLock.lock();
244
Jeff Browne7d54f82015-03-12 19:32:39 -0700245 // Rebuild epoll set if needed.
246 if (mEpollRebuildRequired) {
247 mEpollRebuildRequired = false;
248 rebuildEpollLocked();
249 goto Done;
250 }
251
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800252 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700253 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700254 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700255 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700256 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700257 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800258 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700259 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700260 }
261
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800262 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700263 if (eventCount == 0) {
264#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000265 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700266#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800267 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700268 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700269 }
270
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800271 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700272#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000273 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700274#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700275
Jeff Brown9da18102010-09-17 17:01:23 -0700276 for (int i = 0; i < eventCount; i++) {
277 int fd = eventItems[i].data.fd;
278 uint32_t epollEvents = eventItems[i].events;
Josh Gao2d08ae52018-07-18 17:26:24 -0700279 if (fd == mWakeEventFd.get()) {
Jeff Brown9da18102010-09-17 17:01:23 -0700280 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700281 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700282 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700283 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700284 }
285 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700286 ssize_t requestIndex = mRequests.indexOfKey(fd);
287 if (requestIndex >= 0) {
288 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800289 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
290 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
291 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
292 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700293 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700294 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000295 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700296 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700297 }
298 }
299 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700300Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700301
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800302 // Invoke pending message callbacks.
303 mNextMessageUptime = LLONG_MAX;
304 while (mMessageEnvelopes.size() != 0) {
305 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
306 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
307 if (messageEnvelope.uptime <= now) {
308 // Remove the envelope from the list.
309 // We keep a strong reference to the handler until the call to handleMessage
310 // finishes. Then we drop it so that the handler can be deleted *before*
311 // we reacquire our lock.
312 { // obtain handler
313 sp<MessageHandler> handler = messageEnvelope.handler;
314 Message message = messageEnvelope.message;
315 mMessageEnvelopes.removeAt(0);
316 mSendingMessage = true;
317 mLock.unlock();
318
319#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000320 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800321 this, handler.get(), message.what);
322#endif
323 handler->handleMessage(message);
324 } // release handler
325
326 mLock.lock();
327 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800328 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800329 } else {
330 // The last message left at the head of the queue determines the next wakeup time.
331 mNextMessageUptime = messageEnvelope.uptime;
332 break;
333 }
334 }
335
336 // Release lock.
337 mLock.unlock();
338
339 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700340 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700341 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800342 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800343 int fd = response.request.fd;
344 int events = response.events;
345 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700346#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000347 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700348 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700349#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700350 // Invoke the callback. Note that the file descriptor may be closed by
351 // the callback (and potentially even reused) before the function returns so
352 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700353 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700354 if (callbackResult == 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700355 removeFd(fd, response.request.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700356 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700357
Jeff Browndd1b0372012-05-31 16:15:35 -0700358 // Clear the callback reference in the response structure promptly because we
359 // will not clear the response vector itself until the next poll.
360 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800361 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700362 }
363 }
364 return result;
365}
366
367int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
368 if (timeoutMillis <= 0) {
369 int result;
370 do {
371 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800372 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700373 return result;
374 } else {
375 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
376 + milliseconds_to_nanoseconds(timeoutMillis);
377
378 for (;;) {
379 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800380 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700381 return result;
382 }
383
Jeff Brown43550ee2011-03-17 01:34:19 -0700384 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
385 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
386 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800387 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700388 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700389 }
390 }
391}
392
393void Looper::wake() {
394#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000395 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700396#endif
397
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700398 uint64_t inc = 1;
Josh Gao2d08ae52018-07-18 17:26:24 -0700399 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd.get(), &inc, sizeof(uint64_t)));
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700400 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700401 if (errno != EAGAIN) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700402 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d: %s", mWakeEventFd.get(),
403 strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700404 }
405 }
406}
407
Jeff Brown8d15c742010-10-05 15:35:37 -0700408void Looper::awoken() {
409#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000410 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700411#endif
412
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700413 uint64_t counter;
Josh Gao2d08ae52018-07-18 17:26:24 -0700414 TEMP_FAILURE_RETRY(read(mWakeEventFd.get(), &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700415}
416
417void Looper::pushResponse(int events, const Request& request) {
418 Response response;
419 response.events = events;
420 response.request = request;
421 mResponses.push(response);
422}
423
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800424int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Yi Konge1731a42018-07-16 18:11:34 -0700425 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : nullptr, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700426}
427
428int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700429#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000430 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700431 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700432#endif
433
Jeff Browndd1b0372012-05-31 16:15:35 -0700434 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700435 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000436 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700437 return -1;
438 }
439
440 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700441 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700442 return -1;
443 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700444 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800445 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700446 }
447
448 { // acquire lock
449 AutoMutex _l(mLock);
450
451 Request request;
452 request.fd = fd;
453 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700454 request.events = events;
455 request.seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700456 request.callback = callback;
457 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700458 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700459
460 struct epoll_event eventItem;
Jeff Browne7d54f82015-03-12 19:32:39 -0700461 request.initEventItem(&eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700462
463 ssize_t requestIndex = mRequests.indexOfKey(fd);
464 if (requestIndex < 0) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700465 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700466 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700467 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700468 return -1;
469 }
470 mRequests.add(fd, request);
471 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700472 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700473 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700474 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700475 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700476 // closed before its callback was unregistered and meanwhile a new
477 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700478 // being registered for the first time. This error may occur naturally
479 // when a callback has the side-effect of closing the file descriptor
480 // before returning and unregistering itself. Callback sequence number
481 // checks further ensure that the race is benign.
482 //
483 // Unfortunately due to kernel limitations we need to rebuild the epoll
484 // set from scratch because it may contain an old file handle that we are
485 // now unable to remove since its file descriptor is no longer valid.
486 // No such problem would have occurred if we were using the poll system
487 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700488#if DEBUG_CALLBACKS
489 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700490 "being recycled, falling back on EPOLL_CTL_ADD: %s",
491 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700492#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700493 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700494 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700495 ALOGE("Error modifying or adding epoll events for fd %d: %s",
496 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700497 return -1;
498 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700499 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700500 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700501 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700502 return -1;
503 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700504 }
505 mRequests.replaceValueAt(requestIndex, request);
506 }
507 } // release lock
508 return 1;
509}
510
511int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700512 return removeFd(fd, -1);
513}
514
515int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700516#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700517 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700518#endif
519
520 { // acquire lock
521 AutoMutex _l(mLock);
522 ssize_t requestIndex = mRequests.indexOfKey(fd);
523 if (requestIndex < 0) {
524 return 0;
525 }
526
Jeff Brown7a0310e2015-03-10 18:31:12 -0700527 // Check the sequence number if one was given.
528 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
529#if DEBUG_CALLBACKS
530 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
531 this, mRequests.valueAt(requestIndex).seq);
532#endif
533 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700534 }
535
Jeff Brown7a0310e2015-03-10 18:31:12 -0700536 // Always remove the FD from the request map even if an error occurs while
537 // updating the epoll set so that we avoid accidentally leaking callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700538 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700539
Josh Gao2d08ae52018-07-18 17:26:24 -0700540 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700541 if (epollResult < 0) {
542 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700543 // Tolerate EBADF or ENOENT when the sequence number is known because it
Jeff Brown7a0310e2015-03-10 18:31:12 -0700544 // means that the file descriptor was closed before its callback was
Jeff Browne7d54f82015-03-12 19:32:39 -0700545 // unregistered. This error may occur naturally when a callback has the
546 // side-effect of closing the file descriptor before returning and
547 // unregistering itself.
548 //
549 // Unfortunately due to kernel limitations we need to rebuild the epoll
550 // set from scratch because it may contain an old file handle that we are
551 // now unable to remove since its file descriptor is no longer valid.
552 // No such problem would have occurred if we were using the poll system
553 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700554#if DEBUG_CALLBACKS
555 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700556 "being closed: %s", this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700557#endif
Jeff Browne7d54f82015-03-12 19:32:39 -0700558 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700559 } else {
Jeff Brown18a574f2015-05-29 17:40:25 -0700560 // Some other error occurred. This is really weird because it means
561 // our list of callbacks got out of sync with the epoll set somehow.
562 // We defensively rebuild the epoll set to avoid getting spurious
563 // notifications with nowhere to go.
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700564 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown18a574f2015-05-29 17:40:25 -0700565 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700566 return -1;
567 }
568 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700569 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700570 return 1;
571}
572
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800573void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700574 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
575 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800576}
577
578void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
579 const Message& message) {
580 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
581 sendMessageAtTime(now + uptimeDelay, handler, message);
582}
583
584void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
585 const Message& message) {
586#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700587 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800588 this, uptime, handler.get(), message.what);
589#endif
590
591 size_t i = 0;
592 { // acquire lock
593 AutoMutex _l(mLock);
594
595 size_t messageCount = mMessageEnvelopes.size();
596 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
597 i += 1;
598 }
599
600 MessageEnvelope messageEnvelope(uptime, handler, message);
601 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
602
603 // Optimization: If the Looper is currently sending a message, then we can skip
604 // the call to wake() because the next thing the Looper will do after processing
605 // messages is to decide when the next wakeup time should be. In fact, it does
606 // not even matter whether this code is running on the Looper thread.
607 if (mSendingMessage) {
608 return;
609 }
610 } // release lock
611
612 // Wake the poll loop only when we enqueue a new message at the head.
613 if (i == 0) {
614 wake();
615 }
616}
617
618void Looper::removeMessages(const sp<MessageHandler>& handler) {
619#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000620 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800621#endif
622
623 { // acquire lock
624 AutoMutex _l(mLock);
625
626 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
627 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
628 if (messageEnvelope.handler == handler) {
629 mMessageEnvelopes.removeAt(i);
630 }
631 }
632 } // release lock
633}
634
635void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
636#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000637 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800638#endif
639
640 { // acquire lock
641 AutoMutex _l(mLock);
642
643 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
644 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
645 if (messageEnvelope.handler == handler
646 && messageEnvelope.message.what == what) {
647 mMessageEnvelopes.removeAt(i);
648 }
649 }
650 } // release lock
651}
652
Jeff Brown27e57212015-02-26 14:16:30 -0800653bool Looper::isPolling() const {
654 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700655}
656
Jeff Browne7d54f82015-03-12 19:32:39 -0700657void Looper::Request::initEventItem(struct epoll_event* eventItem) const {
658 int epollEvents = 0;
659 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
660 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
661
662 memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
663 eventItem->events = epollEvents;
664 eventItem->data.fd = fd;
665}
666
Colin Cross17b5b822016-09-15 18:15:37 -0700667MessageHandler::~MessageHandler() { }
668
669LooperCallback::~LooperCallback() { }
670
Jeff Brown7901eb22010-09-13 23:17:30 -0700671} // namespace android