blob: 1db7b3bf0f01a52c28076ba947b88109be9d399c [file] [log] [blame]
[email protected]449019ca2012-03-14 22:17:001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]61c86c62011-08-02 16:11:162// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]59e69e742013-06-18 20:27:525#include "base/message_loop/message_pump_android.h"
[email protected]61c86c62011-08-02 16:11:166
Michael Thiessend7ae7352018-07-10 00:57:137#include <android/looper.h>
8#include <errno.h>
9#include <fcntl.h>
[email protected]61c86c62011-08-02 16:11:1610#include <jni.h>
Michael Thiessend7ae7352018-07-10 00:57:1311#include <sys/eventfd.h>
12#include <sys/syscall.h>
13#include <sys/types.h>
14#include <unistd.h>
15#include <utility>
[email protected]61c86c62011-08-02 16:11:1616
17#include "base/android/jni_android.h"
[email protected]449019ca2012-03-14 22:17:0018#include "base/android/scoped_java_ref.h"
Michael Thiessend7ae7352018-07-10 00:57:1319#include "base/callback_helpers.h"
[email protected]449019ca2012-03-14 22:17:0020#include "base/lazy_instance.h"
[email protected]61c86c62011-08-02 16:11:1621#include "base/logging.h"
[email protected]8e937c1e2012-06-28 22:57:3022#include "base/run_loop.h"
Michael Thiessend7ae7352018-07-10 00:57:1323
24// Android stripped sys/timerfd.h out of their platform headers, so we have to
25// use syscall to make use of timerfd. Once the min API level is 20, we can
26// directly use timerfd.h.
27#ifndef __NR_timerfd_create
28#error "Unable to find syscall for __NR_timerfd_create"
29#endif
30
31#ifndef TFD_TIMER_ABSTIME
32#define TFD_TIMER_ABSTIME (1 << 0)
33#endif
[email protected]61c86c62011-08-02 16:11:1634
torne86560112016-08-04 15:59:0435using base::android::JavaParamRef;
[email protected]449019ca2012-03-14 22:17:0036using base::android::ScopedJavaLocalRef;
[email protected]61c86c62011-08-02 16:11:1637
Michael Thiessen781ddeb2017-11-15 17:07:2338namespace base {
39
Michael Thiessend7ae7352018-07-10 00:57:1340namespace {
Michael Thiessen781ddeb2017-11-15 17:07:2341
Michael Thiessend7ae7352018-07-10 00:57:1342// See sys/timerfd.h
43int timerfd_create(int clockid, int flags) {
44 return syscall(__NR_timerfd_create, clockid, flags);
Michael Thiessen781ddeb2017-11-15 17:07:2345}
46
Michael Thiessend7ae7352018-07-10 00:57:1347// See sys/timerfd.h
48int timerfd_settime(int ufc,
49 int flags,
50 const struct itimerspec* utmr,
51 struct itimerspec* otmr) {
52 return syscall(__NR_timerfd_settime, ufc, flags, utmr, otmr);
53}
Michael Thiessen781ddeb2017-11-15 17:07:2354
Michael Thiessend7ae7352018-07-10 00:57:1355int NonDelayedLooperCallback(int fd, int events, void* data) {
56 if (events & ALOOPER_EVENT_HANGUP)
57 return 0;
58
59 DCHECK(events & ALOOPER_EVENT_INPUT);
60 MessagePumpForUI* pump = reinterpret_cast<MessagePumpForUI*>(data);
61 pump->OnNonDelayedLooperCallback();
62 return 1; // continue listening for events
63}
64
65int DelayedLooperCallback(int fd, int events, void* data) {
66 if (events & ALOOPER_EVENT_HANGUP)
67 return 0;
68
69 DCHECK(events & ALOOPER_EVENT_INPUT);
70 MessagePumpForUI* pump = reinterpret_cast<MessagePumpForUI*>(data);
71 pump->OnDelayedLooperCallback();
72 return 1; // continue listening for events
73}
74
75} // namespace
76
77MessagePumpForUI::MessagePumpForUI() {
78 // The Android native ALooper uses epoll to poll our file descriptors and wake
79 // us up. We use a simple level-triggered eventfd to signal that non-delayed
80 // work is available, and a timerfd to signal when delayed work is ready to
81 // be run.
82 non_delayed_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
83 CHECK_NE(non_delayed_fd_, -1);
84 DCHECK_EQ(TimeTicks::GetClock(), TimeTicks::Clock::LINUX_CLOCK_MONOTONIC);
85
86 // We can't create the timerfd with TFD_NONBLOCK | TFD_CLOEXEC as we can't
87 // include timerfd.h. See comments above on __NR_timerfd_create. It looks like
88 // they're just aliases to O_NONBLOCK and O_CLOEXEC anyways, so this should be
89 // fine.
90 delayed_fd_ = timerfd_create(CLOCK_MONOTONIC, O_NONBLOCK | O_CLOEXEC);
91 CHECK_NE(delayed_fd_, -1);
92
93 looper_ = ALooper_prepare(0);
94 DCHECK(looper_);
95 // Add a reference to the looper so it isn't deleted on us.
96 ALooper_acquire(looper_);
97 ALooper_addFd(looper_, non_delayed_fd_, 0, ALOOPER_EVENT_INPUT,
98 &NonDelayedLooperCallback, reinterpret_cast<void*>(this));
99 ALooper_addFd(looper_, delayed_fd_, 0, ALOOPER_EVENT_INPUT,
100 &DelayedLooperCallback, reinterpret_cast<void*>(this));
101}
102
103MessagePumpForUI::~MessagePumpForUI() {
104 DCHECK_EQ(ALooper_forThread(), looper_);
105 ALooper_removeFd(looper_, non_delayed_fd_);
106 ALooper_removeFd(looper_, delayed_fd_);
107 ALooper_release(looper_);
108 looper_ = nullptr;
109
110 close(non_delayed_fd_);
111 close(delayed_fd_);
112}
113
114void MessagePumpForUI::OnDelayedLooperCallback() {
115 if (ShouldQuit())
Michael Thiessenfc7067fe2017-11-01 22:33:01116 return;
117
Michael Thiessend7ae7352018-07-10 00:57:13118 // Clear the fd.
119 uint64_t value;
120 int ret = read(delayed_fd_, &value, sizeof(value));
Michael Thiessen7c36083d2018-08-10 20:24:54121
122 // TODO(mthiesse): Figure out how it's possible to hit EAGAIN here.
123 // According to http://man7.org/linux/man-pages/man2/timerfd_create.2.html
124 // EAGAIN only happens if no timer has expired. Also according to the man page
125 // poll only returns readable when a timer has expired. So this function will
126 // only be called when a timer has expired, but reading reveals no timer has
127 // expired...
128 // Quit() and ScheduleDelayedWork() are the only other functions that touch
129 // the timerfd, and they both run on the same thread as this callback, so
130 // there are no obvious timing or multi-threading related issues.
131 DPCHECK(ret >= 0 || errno == EAGAIN);
132
Michael Thiessend7ae7352018-07-10 00:57:13133 delayed_scheduled_time_ = base::TimeTicks();
[email protected]61c86c62011-08-02 16:11:16134
[email protected]97532f3f2014-03-11 09:24:42135 base::TimeTicks next_delayed_work_time;
Michael Thiessen781ddeb2017-11-15 17:07:23136 delegate_->DoDelayedWork(&next_delayed_work_time);
Michael Thiessend7ae7352018-07-10 00:57:13137 if (!next_delayed_work_time.is_null()) {
Michael Thiessen781ddeb2017-11-15 17:07:23138 ScheduleDelayedWork(next_delayed_work_time);
Michael Thiessend7ae7352018-07-10 00:57:13139 }
140 if (ShouldQuit())
141 return;
142 // We may be idle now, so pump the loop to find out.
143 ScheduleWork();
144}
145
146void MessagePumpForUI::OnNonDelayedLooperCallback() {
147 base::TimeTicks next_delayed_work_time;
148 bool did_any_work = false;
149
150 // Runs all native tasks scheduled to run, scheduling delayed work if
151 // necessary.
152 while (true) {
153 bool did_work_this_loop = false;
154 if (ShouldQuit())
155 return;
156 did_work_this_loop = delegate_->DoWork();
157 if (ShouldQuit())
158 return;
159
160 did_work_this_loop |= delegate_->DoDelayedWork(&next_delayed_work_time);
161
162 did_any_work |= did_work_this_loop;
163
164 // If we didn't do any work, we're out of native tasks to run, and we should
165 // return control to the looper to run Java tasks.
166 if (!did_work_this_loop)
167 break;
168 }
169 // If we did any work, return control to the looper to run java tasks before
170 // we call DoIdleWork(). We haven't cleared the fd yet, so we'll get woken up
171 // again soon to check for idle-ness.
172 if (did_any_work)
173 return;
174 if (ShouldQuit())
175 return;
176
177 // Read the file descriptor, resetting its contents to 0 and reading back the
178 // stored value.
179 // See http://man7.org/linux/man-pages/man2/eventfd.2.html
180 uint64_t value = 0;
181 int ret = read(non_delayed_fd_, &value, sizeof(value));
Michael Thiessen7c36083d2018-08-10 20:24:54182 DPCHECK(ret >= 0);
Michael Thiessend7ae7352018-07-10 00:57:13183
184 // If we read a value > 1, it means we lost the race to clear the fd before a
185 // new task was posted. This is okay, we can just re-schedule work.
186 if (value > 1) {
187 ScheduleWork();
188 } else {
189 // At this point, the java looper might not be idle - it's impossible to
190 // know pre-Android-M, so we may end up doing Idle work while java tasks are
191 // still queued up. Note that this won't cause us to fail to run java tasks
192 // using QuitWhenIdle, as the JavaHandlerThread will finish running all
193 // currently scheduled tasks before it quits. Also note that we can't just
194 // add an idle callback to the java looper, as that will fire even if native
195 // tasks are still queued up.
196 DoIdleWork();
197 if (!next_delayed_work_time.is_null()) {
198 ScheduleDelayedWork(next_delayed_work_time);
199 }
200 }
201}
202
203void MessagePumpForUI::DoIdleWork() {
204 if (delegate_->DoIdleWork()) {
205 // If DoIdleWork() resulted in any work, we're not idle yet. We need to pump
206 // the loop here because we may in fact be idle after doing idle work
207 // without any new tasks being queued.
208 ScheduleWork();
209 }
[email protected]61c86c62011-08-02 16:11:16210}
211
[email protected]61c86c62011-08-02 16:11:16212void MessagePumpForUI::Run(Delegate* delegate) {
Michael Thiessend7ae7352018-07-10 00:57:13213 DCHECK(IsTestImplementation());
214 // This function is only called in tests. We manually pump the native looper
215 // which won't run any java tasks.
216 quit_ = false;
217
218 SetDelegate(delegate);
219
220 // Pump the loop once in case we're starting off idle as ALooper_pollOnce will
221 // never return in that case.
222 ScheduleWork();
223 while (true) {
224 // Waits for either the delayed, or non-delayed fds to be signalled, calling
225 // either OnDelayedLooperCallback, or OnNonDelayedLooperCallback,
226 // respectively. This uses Android's Looper implementation, which is based
227 // off of epoll.
228 ALooper_pollOnce(-1, nullptr, nullptr, nullptr);
229 if (quit_)
230 break;
231 }
[email protected]61c86c62011-08-02 16:11:16232}
233
Ran Ji3d6ec662018-07-09 21:18:30234void MessagePumpForUI::Attach(Delegate* delegate) {
Michael Thiessendbeca242017-08-28 21:10:08235 DCHECK(!quit_);
Michael Thiessend7ae7352018-07-10 00:57:13236
237 // Since the Looper is controlled by the UI thread or JavaHandlerThread, we
238 // can't use Run() like we do on other platforms or we would prevent Java
239 // tasks from running. Instead we create and initialize a run loop here, then
240 // return control back to the Looper.
241
242 SetDelegate(delegate);
Michael Thiessen781ddeb2017-11-15 17:07:23243 run_loop_ = std::make_unique<RunLoop>();
[email protected]8e937c1e2012-06-28 22:57:30244 // Since the RunLoop was just created above, BeforeRun should be guaranteed to
245 // return true (it only returns false if the RunLoop has been Quit already).
246 if (!run_loop_->BeforeRun())
247 NOTREACHED();
[email protected]61c86c62011-08-02 16:11:16248}
249
250void MessagePumpForUI::Quit() {
Michael Thiessend7ae7352018-07-10 00:57:13251 if (quit_)
252 return;
253
Michael Thiessendbeca242017-08-28 21:10:08254 quit_ = true;
Michael Thiessen781ddeb2017-11-15 17:07:23255
Michael Thiessend7ae7352018-07-10 00:57:13256 int64_t value;
257 // Clear any pending timer.
258 read(delayed_fd_, &value, sizeof(value));
259 // Clear the eventfd.
260 read(non_delayed_fd_, &value, sizeof(value));
[email protected]61c86c62011-08-02 16:11:16261
[email protected]8e937c1e2012-06-28 22:57:30262 if (run_loop_) {
263 run_loop_->AfterRun();
Michael Thiessen781ddeb2017-11-15 17:07:23264 run_loop_ = nullptr;
[email protected]61c86c62011-08-02 16:11:16265 }
Michael Thiessend7ae7352018-07-10 00:57:13266 if (on_quit_callback_) {
267 std::move(on_quit_callback_).Run();
268 }
[email protected]61c86c62011-08-02 16:11:16269}
270
271void MessagePumpForUI::ScheduleWork() {
Michael Thiessend7ae7352018-07-10 00:57:13272 if (ShouldQuit())
Michael Thiessendbeca242017-08-28 21:10:08273 return;
[email protected]61c86c62011-08-02 16:11:16274
Michael Thiessend7ae7352018-07-10 00:57:13275 // Write (add) 1 to the eventfd. This tells the Looper to wake up and call our
276 // callback, allowing us to run tasks. This also allows us to detect, when we
277 // clear the fd, whether additional work was scheduled after we finished
278 // performing work, but before we cleared the fd, as we'll read back >=2
279 // instead of 1 in that case.
280 // See the eventfd man pages
281 // (http://man7.org/linux/man-pages/man2/eventfd.2.html) for details on how
282 // the read and write APIs for this file descriptor work, specifically without
283 // EFD_SEMAPHORE.
284 uint64_t value = 1;
285 int ret = write(non_delayed_fd_, &value, sizeof(value));
Michael Thiessen7c36083d2018-08-10 20:24:54286 DPCHECK(ret >= 0);
[email protected]61c86c62011-08-02 16:11:16287}
288
289void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
Michael Thiessend7ae7352018-07-10 00:57:13290 if (ShouldQuit())
Michael Thiessendbeca242017-08-28 21:10:08291 return;
Michael Thiessend7ae7352018-07-10 00:57:13292
Michael Thiessen781ddeb2017-11-15 17:07:23293 if (!delayed_scheduled_time_.is_null() &&
294 delayed_work_time >= delayed_scheduled_time_) {
295 return;
296 }
Michael Thiessend7ae7352018-07-10 00:57:13297
Michael Thiessen781ddeb2017-11-15 17:07:23298 DCHECK(!delayed_work_time.is_null());
Michael Thiessen781ddeb2017-11-15 17:07:23299 delayed_scheduled_time_ = delayed_work_time;
Michael Thiessend7ae7352018-07-10 00:57:13300 int64_t nanos = delayed_work_time.since_origin().InNanoseconds();
301 struct itimerspec ts;
302 ts.it_interval.tv_sec = 0; // Don't repeat.
303 ts.it_interval.tv_nsec = 0;
304 ts.it_value.tv_sec = nanos / TimeTicks::kNanosecondsPerSecond;
305 ts.it_value.tv_nsec = nanos % TimeTicks::kNanosecondsPerSecond;
306
307 int ret = timerfd_settime(delayed_fd_, TFD_TIMER_ABSTIME, &ts, nullptr);
Michael Thiessen7c36083d2018-08-10 20:24:54308 DPCHECK(ret >= 0);
Michael Thiessend7ae7352018-07-10 00:57:13309}
310
311void MessagePumpForUI::QuitWhenIdle(base::OnceClosure callback) {
312 DCHECK(!on_quit_callback_);
313 DCHECK(run_loop_);
314 on_quit_callback_ = std::move(callback);
315 run_loop_->QuitWhenIdle();
316 // Pump the loop in case we're already idle.
317 ScheduleWork();
318}
319
320bool MessagePumpForUI::IsTestImplementation() const {
321 return false;
[email protected]61c86c62011-08-02 16:11:16322}
323
[email protected]61c86c62011-08-02 16:11:16324} // namespace base