blob: 20c1e927f21c679eac5f80eb290d44abb85d5329 [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>
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070023#include <string.h>
24#include <unistd.h>
Jeff Brown7901eb22010-09-13 23:17:30 -070025
26
27namespace android {
28
Jeff Brown3e2e38b2011-03-02 14:41:58 -080029// --- WeakMessageHandler ---
30
31WeakMessageHandler::WeakMessageHandler(const wp<MessageHandler>& handler) :
32 mHandler(handler) {
33}
34
Jeff Browndd1b0372012-05-31 16:15:35 -070035WeakMessageHandler::~WeakMessageHandler() {
36}
37
Jeff Brown3e2e38b2011-03-02 14:41:58 -080038void WeakMessageHandler::handleMessage(const Message& message) {
39 sp<MessageHandler> handler = mHandler.promote();
40 if (handler != NULL) {
41 handler->handleMessage(message);
42 }
43}
44
45
Jeff Browndd1b0372012-05-31 16:15:35 -070046// --- SimpleLooperCallback ---
47
Brian Carlstrom1693d7e2013-12-11 22:46:45 -080048SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :
Jeff Browndd1b0372012-05-31 16:15:35 -070049 mCallback(callback) {
50}
51
52SimpleLooperCallback::~SimpleLooperCallback() {
53}
54
55int SimpleLooperCallback::handleEvent(int fd, int events, void* data) {
56 return mCallback(fd, events, data);
57}
58
59
Jeff Brown3e2e38b2011-03-02 14:41:58 -080060// --- Looper ---
61
Jeff Brown7901eb22010-09-13 23:17:30 -070062// Hint for number of file descriptors to be associated with the epoll instance.
63static const int EPOLL_SIZE_HINT = 8;
64
65// Maximum number of file descriptors for which to retrieve poll events each iteration.
66static const int EPOLL_MAX_EVENTS = 16;
67
Jeff Brownd1805182010-09-21 15:11:18 -070068static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;
69static pthread_key_t gTLSKey = 0;
70
Jeff Brown7901eb22010-09-13 23:17:30 -070071Looper::Looper(bool allowNonCallbacks) :
Jeff Brown3e2e38b2011-03-02 14:41:58 -080072 mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
73 mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
Jeff Brown7901eb22010-09-13 23:17:30 -070074 int wakeFds[2];
75 int result = pipe(wakeFds);
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070076 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070077
78 mWakeReadPipeFd = wakeFds[0];
79 mWakeWritePipeFd = wakeFds[1];
80
81 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070082 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking: %s",
83 strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070084
85 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070086 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking: %s",
87 strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -070088
Dianne Hackborn19159f92013-05-06 14:25:20 -070089 mIdling = false;
90
Jeff Brown8d15c742010-10-05 15:35:37 -070091 // Allocate the epoll instance and register the wake pipe.
92 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
Elliott Hughes6ed68cc2015-06-30 08:22:24 -070093 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Jeff Brown8d15c742010-10-05 15:35:37 -070094
Jeff Brown7901eb22010-09-13 23:17:30 -070095 struct epoll_event eventItem;
Jeff Brownd1805182010-09-21 15:11:18 -070096 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
Jeff Brown7901eb22010-09-13 23:17:30 -070097 eventItem.events = EPOLLIN;
98 eventItem.data.fd = mWakeReadPipeFd;
99 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700100 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance: %s",
101 strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700102}
103
104Looper::~Looper() {
105 close(mWakeReadPipeFd);
106 close(mWakeWritePipeFd);
107 close(mEpollFd);
108}
109
Jeff Brownd1805182010-09-21 15:11:18 -0700110void Looper::initTLSKey() {
111 int result = pthread_key_create(& gTLSKey, threadDestructor);
112 LOG_ALWAYS_FATAL_IF(result != 0, "Could not allocate TLS key.");
113}
114
Jeff Brown7901eb22010-09-13 23:17:30 -0700115void Looper::threadDestructor(void *st) {
116 Looper* const self = static_cast<Looper*>(st);
117 if (self != NULL) {
118 self->decStrong((void*)threadDestructor);
119 }
120}
121
122void Looper::setForThread(const sp<Looper>& looper) {
123 sp<Looper> old = getForThread(); // also has side-effect of initializing TLS
124
125 if (looper != NULL) {
126 looper->incStrong((void*)threadDestructor);
127 }
128
Jeff Brownd1805182010-09-21 15:11:18 -0700129 pthread_setspecific(gTLSKey, looper.get());
Jeff Brown7901eb22010-09-13 23:17:30 -0700130
131 if (old != NULL) {
132 old->decStrong((void*)threadDestructor);
133 }
134}
135
136sp<Looper> Looper::getForThread() {
Jeff Brownd1805182010-09-21 15:11:18 -0700137 int result = pthread_once(& gTLSOnce, initTLSKey);
138 LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");
Jeff Brown7901eb22010-09-13 23:17:30 -0700139
Jeff Brownd1805182010-09-21 15:11:18 -0700140 return (Looper*)pthread_getspecific(gTLSKey);
Jeff Brown7901eb22010-09-13 23:17:30 -0700141}
142
143sp<Looper> Looper::prepare(int opts) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800144 bool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;
Jeff Brown7901eb22010-09-13 23:17:30 -0700145 sp<Looper> looper = Looper::getForThread();
146 if (looper == NULL) {
147 looper = new Looper(allowNonCallbacks);
148 Looper::setForThread(looper);
149 }
150 if (looper->getAllowNonCallbacks() != allowNonCallbacks) {
Steve Block61d341b2012-01-05 23:22:43 +0000151 ALOGW("Looper already prepared for this thread with a different value for the "
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800152 "LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700153 }
154 return looper;
155}
156
157bool Looper::getAllowNonCallbacks() const {
158 return mAllowNonCallbacks;
159}
160
161int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
162 int result = 0;
163 for (;;) {
164 while (mResponseIndex < mResponses.size()) {
165 const Response& response = mResponses.itemAt(mResponseIndex++);
Jeff Browndd1b0372012-05-31 16:15:35 -0700166 int ident = response.request.ident;
167 if (ident >= 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800168 int fd = response.request.fd;
169 int events = response.events;
170 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700171#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000172 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800173 "fd=%d, events=0x%x, data=%p",
174 this, ident, fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700175#endif
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800176 if (outFd != NULL) *outFd = fd;
177 if (outEvents != NULL) *outEvents = events;
178 if (outData != NULL) *outData = data;
179 return ident;
Jeff Brown7901eb22010-09-13 23:17:30 -0700180 }
181 }
182
183 if (result != 0) {
184#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000185 ALOGD("%p ~ pollOnce - returning result %d", this, result);
Jeff Brown7901eb22010-09-13 23:17:30 -0700186#endif
187 if (outFd != NULL) *outFd = 0;
Jeff Browndd1b0372012-05-31 16:15:35 -0700188 if (outEvents != NULL) *outEvents = 0;
Jeff Brown7901eb22010-09-13 23:17:30 -0700189 if (outData != NULL) *outData = NULL;
190 return result;
191 }
192
193 result = pollInner(timeoutMillis);
194 }
195}
196
197int Looper::pollInner(int timeoutMillis) {
198#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000199 ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
Jeff Brown7901eb22010-09-13 23:17:30 -0700200#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700201
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800202 // Adjust the timeout based on when the next message is due.
203 if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
204 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown43550ee2011-03-17 01:34:19 -0700205 int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
206 if (messageTimeoutMillis >= 0
207 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
208 timeoutMillis = messageTimeoutMillis;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800209 }
210#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000211 ALOGD("%p ~ pollOnce - next message in %lldns, adjusted timeout: timeoutMillis=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800212 this, mNextMessageUptime - now, timeoutMillis);
213#endif
214 }
215
216 // Poll.
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800217 int result = POLL_WAKE;
Jeff Brown8d15c742010-10-05 15:35:37 -0700218 mResponses.clear();
219 mResponseIndex = 0;
220
Dianne Hackborn19159f92013-05-06 14:25:20 -0700221 // We are about to idle.
222 mIdling = true;
223
Jeff Brown7901eb22010-09-13 23:17:30 -0700224 struct epoll_event eventItems[EPOLL_MAX_EVENTS];
225 int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Brown8d15c742010-10-05 15:35:37 -0700226
Dianne Hackborn19159f92013-05-06 14:25:20 -0700227 // No longer idling.
228 mIdling = false;
229
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800230 // Acquire lock.
231 mLock.lock();
232
233 // Check for poll error.
Jeff Brown7901eb22010-09-13 23:17:30 -0700234 if (eventCount < 0) {
Jeff Brown171bf9e2010-09-16 17:04:52 -0700235 if (errno == EINTR) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700236 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700237 }
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700238 ALOGW("Poll failed with an unexpected error: %s", strerror(errno));
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800239 result = POLL_ERROR;
Jeff Brown8d15c742010-10-05 15:35:37 -0700240 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700241 }
242
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800243 // Check for poll timeout.
Jeff Brown7901eb22010-09-13 23:17:30 -0700244 if (eventCount == 0) {
245#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000246 ALOGD("%p ~ pollOnce - timeout", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700247#endif
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800248 result = POLL_TIMEOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700249 goto Done;
Jeff Brown7901eb22010-09-13 23:17:30 -0700250 }
251
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800252 // Handle all events.
Jeff Brown7901eb22010-09-13 23:17:30 -0700253#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000254 ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
Jeff Brown7901eb22010-09-13 23:17:30 -0700255#endif
Jeff Brown8d15c742010-10-05 15:35:37 -0700256
Jeff Brown9da18102010-09-17 17:01:23 -0700257 for (int i = 0; i < eventCount; i++) {
258 int fd = eventItems[i].data.fd;
259 uint32_t epollEvents = eventItems[i].events;
260 if (fd == mWakeReadPipeFd) {
261 if (epollEvents & EPOLLIN) {
Jeff Brown8d15c742010-10-05 15:35:37 -0700262 awoken();
Jeff Brown7901eb22010-09-13 23:17:30 -0700263 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000264 ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
Jeff Brown9da18102010-09-17 17:01:23 -0700265 }
266 } else {
Jeff Brown9da18102010-09-17 17:01:23 -0700267 ssize_t requestIndex = mRequests.indexOfKey(fd);
268 if (requestIndex >= 0) {
269 int events = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800270 if (epollEvents & EPOLLIN) events |= EVENT_INPUT;
271 if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;
272 if (epollEvents & EPOLLERR) events |= EVENT_ERROR;
273 if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;
Jeff Brown8d15c742010-10-05 15:35:37 -0700274 pushResponse(events, mRequests.valueAt(requestIndex));
Jeff Brown9da18102010-09-17 17:01:23 -0700275 } else {
Steve Block61d341b2012-01-05 23:22:43 +0000276 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
Jeff Brown9da18102010-09-17 17:01:23 -0700277 "no longer registered.", epollEvents, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700278 }
279 }
280 }
Jeff Brown8d15c742010-10-05 15:35:37 -0700281Done: ;
Jeff Brown8d15c742010-10-05 15:35:37 -0700282
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800283 // Invoke pending message callbacks.
284 mNextMessageUptime = LLONG_MAX;
285 while (mMessageEnvelopes.size() != 0) {
286 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
287 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);
288 if (messageEnvelope.uptime <= now) {
289 // Remove the envelope from the list.
290 // We keep a strong reference to the handler until the call to handleMessage
291 // finishes. Then we drop it so that the handler can be deleted *before*
292 // we reacquire our lock.
293 { // obtain handler
294 sp<MessageHandler> handler = messageEnvelope.handler;
295 Message message = messageEnvelope.message;
296 mMessageEnvelopes.removeAt(0);
297 mSendingMessage = true;
298 mLock.unlock();
299
300#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000301 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800302 this, handler.get(), message.what);
303#endif
304 handler->handleMessage(message);
305 } // release handler
306
307 mLock.lock();
308 mSendingMessage = false;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800309 result = POLL_CALLBACK;
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800310 } else {
311 // The last message left at the head of the queue determines the next wakeup time.
312 mNextMessageUptime = messageEnvelope.uptime;
313 break;
314 }
315 }
316
317 // Release lock.
318 mLock.unlock();
319
320 // Invoke all response callbacks.
Jeff Brown7901eb22010-09-13 23:17:30 -0700321 for (size_t i = 0; i < mResponses.size(); i++) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700322 Response& response = mResponses.editItemAt(i);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800323 if (response.request.ident == POLL_CALLBACK) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800324 int fd = response.request.fd;
325 int events = response.events;
326 void* data = response.request.data;
Jeff Brown7901eb22010-09-13 23:17:30 -0700327#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000328 ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",
Jeff Browndd1b0372012-05-31 16:15:35 -0700329 this, response.request.callback.get(), fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700330#endif
Jeff Browndd1b0372012-05-31 16:15:35 -0700331 int callbackResult = response.request.callback->handleEvent(fd, events, data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700332 if (callbackResult == 0) {
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800333 removeFd(fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700334 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700335 // Clear the callback reference in the response structure promptly because we
336 // will not clear the response vector itself until the next poll.
337 response.request.callback.clear();
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800338 result = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700339 }
340 }
341 return result;
342}
343
344int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
345 if (timeoutMillis <= 0) {
346 int result;
347 do {
348 result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800349 } while (result == POLL_CALLBACK);
Jeff Brown7901eb22010-09-13 23:17:30 -0700350 return result;
351 } else {
352 nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)
353 + milliseconds_to_nanoseconds(timeoutMillis);
354
355 for (;;) {
356 int result = pollOnce(timeoutMillis, outFd, outEvents, outData);
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800357 if (result != POLL_CALLBACK) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700358 return result;
359 }
360
Jeff Brown43550ee2011-03-17 01:34:19 -0700361 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
362 timeoutMillis = toMillisecondTimeoutDelay(now, endTime);
363 if (timeoutMillis == 0) {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800364 return POLL_TIMEOUT;
Jeff Brown7901eb22010-09-13 23:17:30 -0700365 }
Jeff Brown7901eb22010-09-13 23:17:30 -0700366 }
367 }
368}
369
370void Looper::wake() {
371#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000372 ALOGD("%p ~ wake", this);
Jeff Brown7901eb22010-09-13 23:17:30 -0700373#endif
374
Jeff Brown171bf9e2010-09-16 17:04:52 -0700375 ssize_t nWrite;
376 do {
377 nWrite = write(mWakeWritePipeFd, "W", 1);
378 } while (nWrite == -1 && errno == EINTR);
379
Jeff Brown7901eb22010-09-13 23:17:30 -0700380 if (nWrite != 1) {
381 if (errno != EAGAIN) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700382 ALOGW("Could not write wake signal: %s", strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700383 }
384 }
385}
386
Jeff Brown8d15c742010-10-05 15:35:37 -0700387void Looper::awoken() {
388#if DEBUG_POLL_AND_WAKE
Steve Blockeb095332011-12-20 16:23:08 +0000389 ALOGD("%p ~ awoken", this);
Jeff Brown8d15c742010-10-05 15:35:37 -0700390#endif
391
Jeff Brown8d15c742010-10-05 15:35:37 -0700392 char buffer[16];
393 ssize_t nRead;
394 do {
395 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
396 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
397}
398
399void Looper::pushResponse(int events, const Request& request) {
400 Response response;
401 response.events = events;
402 response.request = request;
403 mResponses.push(response);
404}
405
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800406int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700407 return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);
408}
409
410int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700411#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000412 ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,
Jeff Browndd1b0372012-05-31 16:15:35 -0700413 events, callback.get(), data);
Jeff Brown7901eb22010-09-13 23:17:30 -0700414#endif
415
Jeff Browndd1b0372012-05-31 16:15:35 -0700416 if (!callback.get()) {
Jeff Brown7901eb22010-09-13 23:17:30 -0700417 if (! mAllowNonCallbacks) {
Steve Block1b781ab2012-01-06 19:20:56 +0000418 ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700419 return -1;
420 }
421
422 if (ident < 0) {
Jeff Browndd1b0372012-05-31 16:15:35 -0700423 ALOGE("Invalid attempt to set NULL callback with ident < 0.");
Jeff Brown7901eb22010-09-13 23:17:30 -0700424 return -1;
425 }
Jeff Browndd1b0372012-05-31 16:15:35 -0700426 } else {
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800427 ident = POLL_CALLBACK;
Jeff Brown7901eb22010-09-13 23:17:30 -0700428 }
429
Jeff Brown8d15c742010-10-05 15:35:37 -0700430 int epollEvents = 0;
Brian Carlstrom1693d7e2013-12-11 22:46:45 -0800431 if (events & EVENT_INPUT) epollEvents |= EPOLLIN;
432 if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;
Jeff Brown8d15c742010-10-05 15:35:37 -0700433
Jeff Brown7901eb22010-09-13 23:17:30 -0700434 { // acquire lock
435 AutoMutex _l(mLock);
436
437 Request request;
438 request.fd = fd;
439 request.ident = ident;
440 request.callback = callback;
441 request.data = data;
442
443 struct epoll_event eventItem;
Jeff Brownd1805182010-09-21 15:11:18 -0700444 memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
Jeff Brown7901eb22010-09-13 23:17:30 -0700445 eventItem.events = epollEvents;
446 eventItem.data.fd = fd;
447
448 ssize_t requestIndex = mRequests.indexOfKey(fd);
449 if (requestIndex < 0) {
450 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);
451 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700452 ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700453 return -1;
454 }
455 mRequests.add(fd, request);
456 } else {
457 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);
458 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700459 ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700460 return -1;
461 }
462 mRequests.replaceValueAt(requestIndex, request);
463 }
464 } // release lock
465 return 1;
466}
467
468int Looper::removeFd(int fd) {
469#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000470 ALOGD("%p ~ removeFd - fd=%d", this, fd);
Jeff Brown7901eb22010-09-13 23:17:30 -0700471#endif
472
473 { // acquire lock
474 AutoMutex _l(mLock);
475 ssize_t requestIndex = mRequests.indexOfKey(fd);
476 if (requestIndex < 0) {
477 return 0;
478 }
479
480 int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, NULL);
481 if (epollResult < 0) {
Elliott Hughes6ed68cc2015-06-30 08:22:24 -0700482 ALOGE("Error removing epoll events for fd %d: %s", fd, strerror(errno));
Jeff Brown7901eb22010-09-13 23:17:30 -0700483 return -1;
484 }
485
486 mRequests.removeItemsAt(requestIndex);
Jeff Brown8d15c742010-10-05 15:35:37 -0700487 } // release lock
Jeff Brown7901eb22010-09-13 23:17:30 -0700488 return 1;
489}
490
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800491void Looper::sendMessage(const sp<MessageHandler>& handler, const Message& message) {
Jeff Brownaa13c1b2011-04-12 22:39:53 -0700492 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
493 sendMessageAtTime(now, handler, message);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800494}
495
496void Looper::sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
497 const Message& message) {
498 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
499 sendMessageAtTime(now + uptimeDelay, handler, message);
500}
501
502void Looper::sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
503 const Message& message) {
504#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000505 ALOGD("%p ~ sendMessageAtTime - uptime=%lld, handler=%p, what=%d",
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800506 this, uptime, handler.get(), message.what);
507#endif
508
509 size_t i = 0;
510 { // acquire lock
511 AutoMutex _l(mLock);
512
513 size_t messageCount = mMessageEnvelopes.size();
514 while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
515 i += 1;
516 }
517
518 MessageEnvelope messageEnvelope(uptime, handler, message);
519 mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
520
521 // Optimization: If the Looper is currently sending a message, then we can skip
522 // the call to wake() because the next thing the Looper will do after processing
523 // messages is to decide when the next wakeup time should be. In fact, it does
524 // not even matter whether this code is running on the Looper thread.
525 if (mSendingMessage) {
526 return;
527 }
528 } // release lock
529
530 // Wake the poll loop only when we enqueue a new message at the head.
531 if (i == 0) {
532 wake();
533 }
534}
535
536void Looper::removeMessages(const sp<MessageHandler>& handler) {
537#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000538 ALOGD("%p ~ removeMessages - handler=%p", this, handler.get());
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800539#endif
540
541 { // acquire lock
542 AutoMutex _l(mLock);
543
544 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
545 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
546 if (messageEnvelope.handler == handler) {
547 mMessageEnvelopes.removeAt(i);
548 }
549 }
550 } // release lock
551}
552
553void Looper::removeMessages(const sp<MessageHandler>& handler, int what) {
554#if DEBUG_CALLBACKS
Steve Blockeb095332011-12-20 16:23:08 +0000555 ALOGD("%p ~ removeMessages - handler=%p, what=%d", this, handler.get(), what);
Jeff Brown3e2e38b2011-03-02 14:41:58 -0800556#endif
557
558 { // acquire lock
559 AutoMutex _l(mLock);
560
561 for (size_t i = mMessageEnvelopes.size(); i != 0; ) {
562 const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(--i);
563 if (messageEnvelope.handler == handler
564 && messageEnvelope.message.what == what) {
565 mMessageEnvelopes.removeAt(i);
566 }
567 }
568 } // release lock
569}
570
Dianne Hackborn19159f92013-05-06 14:25:20 -0700571bool Looper::isIdling() const {
572 return mIdling;
573}
574
Jeff Brown7901eb22010-09-13 23:17:30 -0700575} // namespace android