blob: 952c992f168b94924c7a0627eb9051c781295aa8 [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
16#include <cutils/log.h>
17#include <utils/Looper.h>
18#include <utils/Timers.h>
19
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070020#include <errno.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070021#include <fcntl.h>
Jeff Brown3e2e38b2011-03-02 14:41:58 -080022#include <limits.h>
Jeff Brown7a0310e2015-03-10 18:31:12 -070023#include <inttypes.h>
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070024#include <string.h>
Tim Kilbourn8892ce62015-03-26 14:36:32 -070025#include <sys/eventfd.h>
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070026#include <unistd.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070027
28
29namespace android {
30
Jeff Brown3e2e38b2011-03-02 14:41:58 -080031// --- WeakMessageHandler ---
32
33WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
34 mHandler(handler) {
35}
36
Jeff Browndd1b0372012-05-31 16:15:35 -070037WeakMessageHandler::~WeakMessageHandler() {
38}
39
Jeff Brown3e2e38b2011-03-02 14:41:58 -080040void WeakMessageHandler::handleMessage(const Message& message) {
41 sp<MessageHandler> handler = mHandler.promote();
42 if (handler != NULL) {
43 handler->handleMessage(message);
44 }
45}
46
47
Jeff Browndd1b0372012-05-31 16:15:35 -070048// --- SimpleLooperCallback ---
49
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080050SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070051 mCallback(callback) {
52}
53
54SimpleLooperCallback::~SimpleLooperCallback() {
55}
56
57int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
58 return mCallback(fd, events, data);
59}
60
61
Jeff Brown3e2e38b2011-03-02 14:41:58 -080062// --- Looper ---
63
Jeff Brown7901eb22010-09-13 23:17:30 -070064// Hint for number of file descriptors to be associated with the epoll instance.
65static const int EPOLL_SIZE_HINT = 8;
66
67// Maximum number of file descriptors for which to retrieve poll events each iteration.
68static const int EPOLL_MAX_EVENTS = 16;
69
Jeff Brownd1805182010-09-21 15:11:18 -070070static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
71static pthread_key_t gTLSKey = 0;
72
Jeff Brown7901eb22010-09-13 23:17:30 -070073Looper::Looper(bool allowNonCallbacks) :
Jeff Brown3e2e38b2011-03-02 14:41:58 -080074 mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
Jeff Browne7d54f82015-03-12 19:32:39 -070075 mPolling(false), mEpollFd(-1), mEpollRebuildRequired(false),
Jeff Brown7a0310e2015-03-10 18:31:12 -070076 mNextRequestSeq(0), mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
Nick Kralevichc68c8862015-12-18 20:52:37 -080077 mWakeEventFd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
Elliott Hughes5b8ff092015-06-30 15:17:14 -070078 LOG_ALWAYS_FATAL_IF(mWakeEventFd < 0, "Could not make wake event fd: %s",
79 strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070080
Jeff Browne7d54f82015-03-12 19:32:39 -070081 AutoMutex _l(mLock);
82 rebuildEpollLocked();
Jeff Brown7901eb22010-09-13 23:17:30 -070083}
84
85Looper::~Looper() {
Tim Kilbourn8892ce62015-03-26 14:36:32 -070086 close(mWakeEventFd);
Jeff Browne7d54f82015-03-12 19:32:39 -070087 if (mEpollFd >= 0) {
88 close(mEpollFd);
89 }
Jeff Brown7901eb22010-09-13 23:17:30 -070090}
91
Jeff Brownd1805182010-09-21 15:11:18 -070092void Looper::initTLSKey() {
93 int result = pthread_key_create(& gTLSKey, threadDestructor);
94 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
95}
96
Jeff Brown7901eb22010-09-13 23:17:30 -070097void Looper::threadDestructor(void *st) {
98 Looper* const self = static_cast<Looper*>(st);
99 if (self != NULL) {
100 self->decStrong((void*)threadDestructor);
101 }
102}
103
104void Looper::setForThread(const sp<Looper>& looper) {
105 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
106
107 if (looper != NULL) {
108 looper->incStrong((void*)threadDestructor);
109 }
110
Jeff Brownd1805182010-09-21 15:11:18 -0700111 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700112
113 if (old != NULL) {
114 old->decStrong((void*)threadDestructor);
115 }
116}
117
118sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700119 int result = pthread_once(& gTLSOnce, initTLSKey);
120 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700121
Jeff Brownd1805182010-09-21 15:11:18 -0700122 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700123}
124
125sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800126 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700127 sp<Looper> looper = Looper::getForThread();
128 if (looper == NULL) {
129 looper = new Looper(allowNonCallbacks);
130 Looper::setForThread(looper);
131 }
132 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000133 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800134 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700135 }
136 return looper;
137}
138
139bool Looper::getAllowNonCallbacks() const {
140 return mAllowNonCallbacks;
141}
142
Jeff Browne7d54f82015-03-12 19:32:39 -0700143void Looper::rebuildEpollLocked() {
144 // Close old epoll instance if we have one.
145 if (mEpollFd >= 0) {
146#if DEBUG_CALLBACKS
147 ALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
148#endif
149 close(mEpollFd);
150 }
151
152 // Allocate the new epoll instance and register the wake pipe.
153 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700154 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700155
156 struct epoll_event eventItem;
157 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
158 eventItem.events = EPOLLIN;
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700159 eventItem.data.fd = mWakeEventFd;
160 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem);
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700161 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",
162 strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700163
164 for (size_t i = 0; i < mRequests.size(); i++) {
165 const Request& request = mRequests.valueAt(i);
166 struct epoll_event eventItem;
167 request.initEventItem(&eventItem);
168
169 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, request.fd, & eventItem);
170 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700171 ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",
172 request.fd, strerror(errno));
Jeff Browne7d54f82015-03-12 19:32:39 -0700173 }
174 }
175}
176
177void Looper::scheduleEpollRebuildLocked() {
178 if (!mEpollRebuildRequired) {
179#if DEBUG_CALLBACKS
180 ALOGD("%p ~ scheduleEpollRebuildLocked - scheduling epoll set rebuild", this);
181#endif
182 mEpollRebuildRequired = true;
183 wake();
184 }
185}
186
Jeff Brown7901eb22010-09-13 23:17:30 -0700187int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
188 int result = 0;
189 for (;;) {
190 while (mResponseIndex < mResponses.size()) {
191 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700192 int ident = response.request.ident;
193 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800194 int fd = response.request.fd;
195 int events = response.events;
196 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700197#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000198 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800199 "fd=%d, events=0x%x, data=%p",
200 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700201#endif
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800202 if (outFd != NULL) *outFd = fd;
203 if (outEvents != NULL) *outEvents = events;
204 if (outData != NULL) *outData = data;
205 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700206 }
207 }
208
209 if (result != 0) {
210#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000211 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700212#endif
213 if (outFd != NULL) *outFd = 0;
Jeff Browndd1b0372012-05-31 16:15:35 -0700214 if (outEvents != NULL) *outEvents = 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700215 if (outData != NULL) *outData = NULL;
216 return result;
217 }
218
219 result = pollInner(timeoutMillis);
220 }
221}
222
223int Looper::pollInner(int timeoutMillis) {
224#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000225 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700226#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700227
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800228 // Adjust the timeout based on when the next message is due.
229 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
230 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700231 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
232 if (messageTimeoutMillis >= 0
233 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
234 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800235 }
236#if DEBUG_POLL_AND_WAKE
Jeff Brown7a0310e2015-03-10 18:31:12 -0700237 ALOGD("%p ~ pollOnce - next message in %" PRId64 "ns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800238 this, mNextMessageUptime - now, timeoutMillis);
239#endif
240 }
241
242 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800243 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700244 mResponses.clear();
245 mResponseIndex = 0;
246
Dianne Hackborn19159f92013-05-06 14:25:20 -0700247 // We are about to idle.
Jeff Brown27e57212015-02-26 14:16:30 -0800248 mPolling = true;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700249
Jeff Brown7901eb22010-09-13 23:17:30 -0700250 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
251 int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700252
Dianne Hackborn19159f92013-05-06 14:25:20 -0700253 // No longer idling.
Jeff Brown27e57212015-02-26 14:16:30 -0800254 mPolling = false;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700255
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800256 // Acquire lock.
257 mLock.lock();
258
Jeff Browne7d54f82015-03-12 19:32:39 -0700259 // Rebuild epoll set if needed.
260 if (mEpollRebuildRequired) {
261 mEpollRebuildRequired = false;
262 rebuildEpollLocked();
263 goto Done;
264 }
265
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800266 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700267 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700268 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700269 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700270 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700271 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800272 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700273 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700274 }
275
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800276 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700277 if (eventCount == 0) {
278#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000279 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700280#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800281 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700282 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700283 }
284
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800285 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700286#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000287 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700288#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700289
Jeff Brown9da18102010-09-17 17:01:23 -0700290 for (int i = 0; i < eventCount; i++) {
291 int fd = eventItems[i].data.fd;
292 uint32_t epollEvents = eventItems[i].events;
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700293 if (fd == mWakeEventFd) {
Jeff Brown9da18102010-09-17 17:01:23 -0700294 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700295 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700296 } else {
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700297 ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700298 }
299 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700300 ssize_t requestIndex = mRequests.indexOfKey(fd);
301 if (requestIndex >= 0) {
302 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800303 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
304 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
305 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
306 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700307 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700308 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000309 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700310 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700311 }
312 }
313 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700314Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700315
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800316 // Invoke pending message callbacks.
317 mNextMessageUptime = LLONG_MAX;
318 while (mMessageEnvelopes.size() != 0) {
319 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
320 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
321 if (messageEnvelope.uptime <= now) {
322 // Remove the envelope from the list.
323 // We keep a strong reference to the handler until the call to handleMessage
324 // finishes. Then we drop it so that the handler can be deleted *before*
325 // we reacquire our lock.
326 { // obtain handler
327 sp<MessageHandler> handler = messageEnvelope.handler;
328 Message message = messageEnvelope.message;
329 mMessageEnvelopes.removeAt(0);
330 mSendingMessage = true;
331 mLock.unlock();
332
333#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000334 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800335 this, handler.get(), message.what);
336#endif
337 handler->handleMessage(message);
338 } // release handler
339
340 mLock.lock();
341 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800342 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800343 } else {
344 // The last message left at the head of the queue determines the next wakeup time.
345 mNextMessageUptime = messageEnvelope.uptime;
346 break;
347 }
348 }
349
350 // Release lock.
351 mLock.unlock();
352
353 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700354 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700355 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800356 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800357 int fd = response.request.fd;
358 int events = response.events;
359 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700360#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000361 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700362 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700363#endif
Jeff Brown7a0310e2015-03-10 18:31:12 -0700364 // Invoke the callback. Note that the file descriptor may be closed by
365 // the callback (and potentially even reused) before the function returns so
366 // we need to be a little careful when removing the file descriptor afterwards.
Jeff Browndd1b0372012-05-31 16:15:35 -0700367 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700368 if (callbackResult == 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700369 removeFd(fd, response.request.seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700370 }
Jeff Brown7a0310e2015-03-10 18:31:12 -0700371
Jeff Browndd1b0372012-05-31 16:15:35 -0700372 // Clear the callback reference in the response structure promptly because we
373 // will not clear the response vector itself until the next poll.
374 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800375 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700376 }
377 }
378 return result;
379}
380
381int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
382 if (timeoutMillis <= 0) {
383 int result;
384 do {
385 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800386 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700387 return result;
388 } else {
389 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
390 + milliseconds_to_nanoseconds(timeoutMillis);
391
392 for (;;) {
393 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800394 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700395 return result;
396 }
397
Jeff Brown43550ee2011-03-17 01:34:19 -0700398 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
399 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
400 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800401 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700402 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700403 }
404 }
405}
406
407void Looper::wake() {
408#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000409 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700410#endif
411
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700412 uint64_t inc = 1;
413 ssize_t nWrite = TEMP_FAILURE_RETRY(write(mWakeEventFd, &inc, sizeof(uint64_t)));
414 if (nWrite != sizeof(uint64_t)) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700415 if (errno != EAGAIN) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700416 ALOGW("Could not write wake signal: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700417 }
418 }
419}
420
Jeff Brown8d15c742010-10-05 15:35:37 -0700421void Looper::awoken() {
422#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000423 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700424#endif
425
Tim Kilbourn8892ce62015-03-26 14:36:32 -0700426 uint64_t counter;
427 TEMP_FAILURE_RETRY(read(mWakeEventFd, &counter, sizeof(uint64_t)));
Jeff Brown8d15c742010-10-05 15:35:37 -0700428}
429
430void Looper::pushResponse(int events, const Request& request) {
431 Response response;
432 response.events = events;
433 response.request = request;
434 mResponses.push(response);
435}
436
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800437int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700438 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);
439}
440
441int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700442#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000443 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700444 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700445#endif
446
Jeff Browndd1b0372012-05-31 16:15:35 -0700447 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700448 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000449 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700450 return -1;
451 }
452
453 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700454 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700455 return -1;
456 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700457 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800458 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700459 }
460
461 { // acquire lock
462 AutoMutex _l(mLock);
463
464 Request request;
465 request.fd = fd;
466 request.ident = ident;
Jeff Browne7d54f82015-03-12 19:32:39 -0700467 request.events = events;
468 request.seq = mNextRequestSeq++;
Jeff Brown7901eb22010-09-13 23:17:30 -0700469 request.callback = callback;
470 request.data = data;
Jeff Brown7a0310e2015-03-10 18:31:12 -0700471 if (mNextRequestSeq == -1) mNextRequestSeq = 0; // reserve sequence number -1
Jeff Brown7901eb22010-09-13 23:17:30 -0700472
473 struct epoll_event eventItem;
Jeff Browne7d54f82015-03-12 19:32:39 -0700474 request.initEventItem(&eventItem);
Jeff Brown7901eb22010-09-13 23:17:30 -0700475
476 ssize_t requestIndex = mRequests.indexOfKey(fd);
477 if (requestIndex < 0) {
478 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
479 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700480 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700481 return -1;
482 }
483 mRequests.add(fd, request);
484 } else {
485 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
486 if (epollResult < 0) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700487 if (errno == ENOENT) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700488 // Tolerate ENOENT because it means that an older file descriptor was
Jeff Brown7a0310e2015-03-10 18:31:12 -0700489 // closed before its callback was unregistered and meanwhile a new
490 // file descriptor with the same number has been created and is now
Jeff Browne7d54f82015-03-12 19:32:39 -0700491 // being registered for the first time. This error may occur naturally
492 // when a callback has the side-effect of closing the file descriptor
493 // before returning and unregistering itself. Callback sequence number
494 // checks further ensure that the race is benign.
495 //
496 // Unfortunately due to kernel limitations we need to rebuild the epoll
497 // set from scratch because it may contain an old file handle that we are
498 // now unable to remove since its file descriptor is no longer valid.
499 // No such problem would have occurred if we were using the poll system
500 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700501#if DEBUG_CALLBACKS
502 ALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700503 "being recycled, falling back on EPOLL_CTL_ADD: %s",
504 this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700505#endif
506 epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
507 if (epollResult < 0) {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700508 ALOGE("Error modifying or adding epoll events for fd %d: %s",
509 fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700510 return -1;
511 }
Jeff Browne7d54f82015-03-12 19:32:39 -0700512 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700513 } else {
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700514 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700515 return -1;
516 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700517 }
518 mRequests.replaceValueAt(requestIndex, request);
519 }
520 } // release lock
521 return 1;
522}
523
524int Looper::removeFd(int fd) {
Jeff Brown7a0310e2015-03-10 18:31:12 -0700525 return removeFd(fd, -1);
526}
527
528int Looper::removeFd(int fd, int seq) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700529#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700530 ALOGD("%p ~ removeFd - fd=%d, seq=%d", this, fd, seq);
Jeff Brown7901eb22010-09-13 23:17:30 -0700531#endif
532
533 { // acquire lock
534 AutoMutex _l(mLock);
535 ssize_t requestIndex = mRequests.indexOfKey(fd);
536 if (requestIndex < 0) {
537 return 0;
538 }
539
Jeff Brown7a0310e2015-03-10 18:31:12 -0700540 // Check the sequence number if one was given.
541 if (seq != -1 && mRequests.valueAt(requestIndex).seq != seq) {
542#if DEBUG_CALLBACKS
543 ALOGD("%p ~ removeFd - sequence number mismatch, oldSeq=%d",
544 this, mRequests.valueAt(requestIndex).seq);
545#endif
546 return 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700547 }
548
Jeff Brown7a0310e2015-03-10 18:31:12 -0700549 // Always remove the FD from the request map even if an error occurs while
550 // updating the epoll set so that we avoid accidentally leaking callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700551 mRequests.removeItemsAt(requestIndex);
Jeff Brown7a0310e2015-03-10 18:31:12 -0700552
553 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, NULL);
554 if (epollResult < 0) {
555 if (seq != -1 && (errno == EBADF || errno == ENOENT)) {
Jeff Browne7d54f82015-03-12 19:32:39 -0700556 // Tolerate EBADF or ENOENT when the sequence number is known because it
Jeff Brown7a0310e2015-03-10 18:31:12 -0700557 // means that the file descriptor was closed before its callback was
Jeff Browne7d54f82015-03-12 19:32:39 -0700558 // unregistered. This error may occur naturally when a callback has the
559 // side-effect of closing the file descriptor before returning and
560 // unregistering itself.
561 //
562 // Unfortunately due to kernel limitations we need to rebuild the epoll
563 // set from scratch because it may contain an old file handle that we are
564 // now unable to remove since its file descriptor is no longer valid.
565 // No such problem would have occurred if we were using the poll system
566 // call instead, but that approach carries others disadvantages.
Jeff Brown7a0310e2015-03-10 18:31:12 -0700567#if DEBUG_CALLBACKS
568 ALOGD("%p ~ removeFd - EPOLL_CTL_DEL failed due to file descriptor "
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700569 "being closed: %s", this, strerror(errno));
Jeff Brown7a0310e2015-03-10 18:31:12 -0700570#endif
Jeff Browne7d54f82015-03-12 19:32:39 -0700571 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700572 } else {
Jeff Brown18a574f2015-05-29 17:40:25 -0700573 // Some other error occurred. This is really weird because it means
574 // our list of callbacks got out of sync with the epoll set somehow.
575 // We defensively rebuild the epoll set to avoid getting spurious
576 // notifications with nowhere to go.
Elliott Hughes5b8ff092015-06-30 15:17:14 -0700577 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown18a574f2015-05-29 17:40:25 -0700578 scheduleEpollRebuildLocked();
Jeff Brown7a0310e2015-03-10 18:31:12 -0700579 return -1;
580 }
581 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700582 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700583 return 1;
584}
585
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800586void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700587 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
588 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800589}
590
591void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
592 const Message& message) {
593 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
594 sendMessageAtTime(now + uptimeDelay, handler, message);
595}
596
597void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
598 const Message& message) {
599#if DEBUG_CALLBACKS
Jeff Brown7a0310e2015-03-10 18:31:12 -0700600 ALOGD("%p ~ sendMessageAtTime - uptime=%" PRId64 ", handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800601 this, uptime, handler.get(), message.what);
602#endif
603
604 size_t i = 0;
605 { // acquire lock
606 AutoMutex _l(mLock);
607
608 size_t messageCount = mMessageEnvelopes.size();
609 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
610 i += 1;
611 }
612
613 MessageEnvelope messageEnvelope(uptime, handler, message);
614 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
615
616 // Optimization: If the Looper is currently sending a message, then we can skip
617 // the call to wake() because the next thing the Looper will do after processing
618 // messages is to decide when the next wakeup time should be. In fact, it does
619 // not even matter whether this code is running on the Looper thread.
620 if (mSendingMessage) {
621 return;
622 }
623 } // release lock
624
625 // Wake the poll loop only when we enqueue a new message at the head.
626 if (i == 0) {
627 wake();
628 }
629}
630
631void Looper::removeMessages(const sp<MessageHandler>& handler) {
632#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000633 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800634#endif
635
636 { // acquire lock
637 AutoMutex _l(mLock);
638
639 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
640 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
641 if (messageEnvelope.handler == handler) {
642 mMessageEnvelopes.removeAt(i);
643 }
644 }
645 } // release lock
646}
647
648void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
649#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000650 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800651#endif
652
653 { // acquire lock
654 AutoMutex _l(mLock);
655
656 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
657 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
658 if (messageEnvelope.handler == handler
659 && messageEnvelope.message.what == what) {
660 mMessageEnvelopes.removeAt(i);
661 }
662 }
663 } // release lock
664}
665
Jeff Brown27e57212015-02-26 14:16:30 -0800666bool Looper::isPolling() const {
667 return mPolling;
Dianne Hackborn19159f92013-05-06 14:25:20 -0700668}
669
Jeff Browne7d54f82015-03-12 19:32:39 -0700670void Looper::Request::initEventItem(struct epoll_event* eventItem) const {
671 int epollEvents = 0;
672 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
673 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
674
675 memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
676 eventItem->events = epollEvents;
677 eventItem->data.fd = fd;
678}
679
Jeff Brown7901eb22010-09-13 23:17:30 -0700680} // namespace android