blob: 102fdf037a173a8950edddcd8aa8d18e786f0e74 [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// Hint for number of file descriptors to be associated with the epoll instance.
55static const int EPOLL_SIZE_HINT = 8;
56
57// Maximum number of file descriptors for which to retrieve poll events each iteration.
58static const int EPOLL_MAX_EVENTS = 16;
59
Jeff Brownd1805182010-09-21 15:11:18 -070060static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
61static pthread_key_t gTLSKey = 0;
62
Josh Gao2d08ae52018-07-18 17:26:24 -070063Looper::Looper(bool allowNonCallbacks)
64 : mAllowNonCallbacks(allowNonCallbacks),
65 mSendingMessage(false),
66 mPolling(false),
67 mEpollRebuildRequired(false),
68 mNextRequestSeq(0),
69 mResponseIndex(0),
70 mNextMessageUptime(LLONG_MAX) {
71 mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
72 LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070073
Jeff Browne7d54f82015-03-12 19:32:39 -070074 AutoMutex _l(mLock);
75 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070076}
77
78Looper::~Looper() {
Jeff Brown7901eb22010-09-13 23:17:30 -070079}
80
Jeff Brownd1805182010-09-21 15:11:18 -070081void Looper::initTLSKey() {
82 int result = pthread_key_create(& gTLSKey, threadDestructor);
83 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
84}
85
Jeff Brown7901eb22010-09-13 23:17:30 -070086void Looper::threadDestructor(void *st) {
87 Looper* const self = static_cast<Looper*>(st);
Yi Konge1731a42018-07-16 18:11:34 -070088 if (self != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070089 self->decStrong((void*)threadDestructor);
90 }
91}
92
93void Looper::setForThread(const sp<Looper>& looper) {
94 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
95
Yi Konge1731a42018-07-16 18:11:34 -070096 if (looper != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -070097 looper->incStrong((void*)threadDestructor);
98 }
99
Jeff Brownd1805182010-09-21 15:11:18 -0700100 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700101
Yi Konge1731a42018-07-16 18:11:34 -0700102 if (old != nullptr) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700103 old->decStrong((void*)threadDestructor);
104 }
105}
106
107sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700108 int result = pthread_once(& gTLSOnce, initTLSKey);
109 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700110
Jeff Brownd1805182010-09-21 15:11:18 -0700111 return (Looper*)pthread_getspecific(gTLSKey);
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) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700118 looper = new Looper(allowNonCallbacks);
119 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.
Josh Gao2d08ae52018-07-18 17:26:24 -0700142 mEpollFd.reset(epoll_create(EPOLL_SIZE_HINT));
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) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700405 LOG_ALWAYS_FATAL("Could not write wake signal to fd %d: %s", mWakeEventFd.get(),
406 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) {
Yi Konge1731a42018-07-16 18:11:34 -0700428 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : nullptr, data);
Jeff Browndd1b0372012-05-31 16:15:35 -0700429}
430
431int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700432#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000433 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700434 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700435#endif
436
Jeff Browndd1b0372012-05-31 16:15:35 -0700437 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700438 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000439 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700440 return -1;
441 }
442
443 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700444 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700445 return -1;
446 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700447 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800448 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700449 }
450
451 { // acquire lock
452 AutoMutex _l(mLock);
453
454 Request request;
455 request.fd = fd;
456 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700457 request.events = events;
458 request.seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700459 request.callback = callback;
460 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700461 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700462
463 struct epoll_event eventItem;
Jeff Browne7d54f82015-03-12 19:32:39 -0700464 request.initEventItem(&eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700465
466 ssize_t requestIndex = mRequests.indexOfKey(fd);
467 if (requestIndex < 0) {
Josh Gao2d08ae52018-07-18 17:26:24 -0700468 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700469 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700470 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700471 return -1;
472 }
473 mRequests.add(fd, request);
474 } else {
Josh Gao2d08ae52018-07-18 17:26:24 -0700475 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700476 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700477 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700478 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700479 // closed before its callback was unregistered and meanwhile a new
480 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700481 // being registered for the first time. This error may occur naturally
482 // when a callback has the side-effect of closing the file descriptor
483 // before returning and unregistering itself. Callback sequence number
484 // checks further ensure that the race is benign.
485 //
486 // Unfortunately due to kernel limitations we need to rebuild the epoll
487 // set from scratch because it may contain an old file handle that we are
488 // now unable to remove since its file descriptor is no longer valid.
489 // No such problem would have occurred if we were using the poll system
490 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700491#if DEBUG_CALLBACKS
492 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700493 "being recycled, falling back on EPOLL_CTL_ADD: %s",
494 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700495#endif
Josh Gao2d08ae52018-07-18 17:26:24 -0700496 epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700497 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700498 ALOGE("Error modifying or adding epoll events for fd %d: %s",
499 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700500 return -1;
501 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700502 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700503 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700504 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700505 return -1;
506 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700507 }
508 mRequests.replaceValueAt(requestIndex, request);
509 }
510 } // release lock
511 return 1;
512}
513
514int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700515 return removeFd(fd, -1);
516}
517
518int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700519#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700520 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700521#endif
522
523 { // acquire lock
524 AutoMutex _l(mLock);
525 ssize_t requestIndex = mRequests.indexOfKey(fd);
526 if (requestIndex < 0) {
527 return 0;
528 }
529
Jeff Brown7a0310e2015-03-10 18:31:12 -0700530 // Check the sequence number if one was given.
531 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
532#if DEBUG_CALLBACKS
533 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
534 this, mRequests.valueAt(requestIndex).seq);
535#endif
536 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700537 }
538
Jeff Brown7a0310e2015-03-10 18:31:12 -0700539 // Always remove the FD from the request map even if an error occurs while
540 // updating the epoll set so that we avoid accidentally leaking callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700541 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700542
Josh Gao2d08ae52018-07-18 17:26:24 -0700543 int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_DEL, fd, nullptr);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700544 if (epollResult < 0) {
545 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700546 // Tolerate EBADF or ENOENT when the sequence number is known because it
Jeff Brown7a0310e2015-03-10 18:31:12 -0700547 // means that the file descriptor was closed before its callback was
Jeff Browne7d54f82015-03-12 19:32:39 -0700548 // unregistered. This error may occur naturally when a callback has the
549 // side-effect of closing the file descriptor before returning and
550 // unregistering itself.
551 //
552 // Unfortunately due to kernel limitations we need to rebuild the epoll
553 // set from scratch because it may contain an old file handle that we are
554 // now unable to remove since its file descriptor is no longer valid.
555 // No such problem would have occurred if we were using the poll system
556 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700557#if DEBUG_CALLBACKS
558 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700559 "being closed: %s", this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700560#endif
Jeff Browne7d54f82015-03-12 19:32:39 -0700561 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700562 } else {
Jeff Brown18a574f2015-05-29 17:40:25 -0700563 // Some other error occurred. This is really weird because it means
564 // our list of callbacks got out of sync with the epoll set somehow.
565 // We defensively rebuild the epoll set to avoid getting spurious
566 // notifications with nowhere to go.
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700567 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown18a574f2015-05-29 17:40:25 -0700568 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700569 return -1;
570 }
571 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700572 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700573 return 1;
574}
575
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800576void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700577 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
578 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800579}
580
581void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
582 const Message& message) {
583 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
584 sendMessageAtTime(now + uptimeDelay, handler, message);
585}
586
587void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
588 const Message& message) {
589#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700590 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800591 this, uptime, handler.get(), message.what);
592#endif
593
594 size_t i = 0;
595 { // acquire lock
596 AutoMutex _l(mLock);
597
598 size_t messageCount = mMessageEnvelopes.size();
599 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
600 i += 1;
601 }
602
603 MessageEnvelope messageEnvelope(uptime, handler, message);
604 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
605
606 // Optimization: If the Looper is currently sending a message, then we can skip
607 // the call to wake() because the next thing the Looper will do after processing
608 // messages is to decide when the next wakeup time should be. In fact, it does
609 // not even matter whether this code is running on the Looper thread.
610 if (mSendingMessage) {
611 return;
612 }
613 } // release lock
614
615 // Wake the poll loop only when we enqueue a new message at the head.
616 if (i == 0) {
617 wake();
618 }
619}
620
621void Looper::removeMessages(const sp<MessageHandler>& handler) {
622#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000623 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800624#endif
625
626 { // acquire lock
627 AutoMutex _l(mLock);
628
629 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
630 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
631 if (messageEnvelope.handler == handler) {
632 mMessageEnvelopes.removeAt(i);
633 }
634 }
635 } // release lock
636}
637
638void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
639#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000640 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800641#endif
642
643 { // acquire lock
644 AutoMutex _l(mLock);
645
646 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
647 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
648 if (messageEnvelope.handler == handler
649 && messageEnvelope.message.what == what) {
650 mMessageEnvelopes.removeAt(i);
651 }
652 }
653 } // release lock
654}
655
Jeff Brown27e57212015-02-26 14:16:30 -0800656bool Looper::isPolling() const {
657 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700658}
659
Jeff Browne7d54f82015-03-12 19:32:39 -0700660void Looper::Request::initEventItem(struct epoll_event* eventItem) const {
661 int epollEvents = 0;
662 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
663 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
664
665 memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
666 eventItem->events = epollEvents;
667 eventItem->data.fd = fd;
668}
669
Colin Cross17b5b822016-09-15 18:15:37 -0700670MessageHandler::~MessageHandler() { }
671
672LooperCallback::~LooperCallback() { }
673
Jeff Brown7901eb22010-09-13 23:17:30 -0700674} // namespace android