blob: 32f908636891f6e9f82c0533c830d22c267ecf4f [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/* http://frotznet.googlecode.com/svn/trunk/utils/fdevent.c
2**
3** Copyright 2006, Brian Swetland <swetland@frotz.net>
4**
Elliott Hughesaa245492015-08-03 10:38:08 -07005** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08008**
Elliott Hughesaa245492015-08-03 10:38:08 -07009** http://www.apache.org/licenses/LICENSE-2.0
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080010**
Elliott Hughesaa245492015-08-03 10:38:08 -070011** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080015** limitations under the License.
16*/
17
Yabin Cuiaed3c612015-09-22 15:52:57 -070018#define TRACE_TAG FDEVENT
JP Abgrall408fa572011-03-16 15:57:42 -070019
Dan Albert33134262015-03-19 15:21:08 -070020#include "sysdeps.h"
21#include "fdevent.h"
22
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080023#include <fcntl.h>
Josh Gaoded557f2018-06-18 14:55:27 -070024#include <inttypes.h>
Josh Gao5791e212018-03-16 14:25:42 -070025#include <stdint.h>
Dan Albert33134262015-03-19 15:21:08 -070026#include <stdlib.h>
27#include <string.h>
Dan Albert33134262015-03-19 15:21:08 -070028#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080029
Josh Gao022d4472016-02-10 14:49:00 -080030#include <atomic>
Josh Gaoe39ccd32018-02-23 14:37:07 -080031#include <deque>
Josh Gao4c936392017-05-03 14:10:39 -070032#include <functional>
Yabin Cuia1080162015-09-04 16:19:56 -070033#include <list>
Josh Gao4c936392017-05-03 14:10:39 -070034#include <mutex>
Josh Gao1a901182019-01-31 15:51:52 -080035#include <optional>
Yabin Cuia1080162015-09-04 16:19:56 -070036#include <unordered_map>
Josh Gaoc162c712019-01-25 15:30:25 -080037#include <utility>
38#include <variant>
Yabin Cuia1080162015-09-04 16:19:56 -070039#include <vector>
40
Josh Gao39c1f4b2018-10-05 17:09:07 -070041#include <android-base/chrono_utils.h>
42#include <android-base/file.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080043#include <android-base/logging.h>
44#include <android-base/stringprintf.h>
Josh Gao4c936392017-05-03 14:10:39 -070045#include <android-base/thread_annotations.h>
Josh Gao5791e212018-03-16 14:25:42 -070046#include <android-base/threads.h>
Yabin Cuia1080162015-09-04 16:19:56 -070047
Dan Albertcc731cc2015-02-24 21:26:58 -080048#include "adb_io.h"
leozwangd3fc15f2014-07-29 12:50:02 -070049#include "adb_trace.h"
Josh Gao4c936392017-05-03 14:10:39 -070050#include "adb_unique_fd.h"
Yabin Cui6dfef252015-10-06 15:10:05 -070051#include "adb_utils.h"
Josh Gao39c1f4b2018-10-05 17:09:07 -070052#include "sysdeps/chrono.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080053
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054#define FDE_EVENTMASK 0x00ff
55#define FDE_STATEMASK 0xff00
56
57#define FDE_ACTIVE 0x0100
58#define FDE_PENDING 0x0200
59#define FDE_CREATED 0x0400
60
Yabin Cuia1080162015-09-04 16:19:56 -070061struct PollNode {
62 fdevent* fde;
Josh Gao3777d2e2016-02-16 17:34:53 -080063 adb_pollfd pollfd;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080064
Chih-Hung Hsieh1c563d92016-04-29 15:44:04 -070065 explicit PollNode(fdevent* fde) : fde(fde) {
Yabin Cuia1080162015-09-04 16:19:56 -070066 memset(&pollfd, 0, sizeof(pollfd));
Josh Gao3b37fa22018-05-14 13:42:49 -070067 pollfd.fd = fde->fd.get();
Yabin Cuiaa77e222015-09-29 12:25:33 -070068
69#if defined(__linux__)
70 // Always enable POLLRDHUP, so the host server can take action when some clients disconnect.
71 // Then we can avoid leaving many sockets in CLOSE_WAIT state. See http://b/23314034.
72 pollfd.events = POLLRDHUP;
73#endif
Yabin Cuia1080162015-09-04 16:19:56 -070074 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080075};
76
Yabin Cuia1080162015-09-04 16:19:56 -070077// All operations to fdevent should happen only in the main thread.
78// That's why we don't need a lock for fdevent.
Josh Gaob7b1edf2015-11-11 17:56:12 -080079static auto& g_poll_node_map = *new std::unordered_map<int, PollNode>();
80static auto& g_pending_list = *new std::list<fdevent*>();
Josh Gao022d4472016-02-10 14:49:00 -080081static std::atomic<bool> terminate_loop(false);
Yabin Cuifbfa8402015-10-30 18:37:26 -070082static bool main_thread_valid;
Josh Gao5791e212018-03-16 14:25:42 -070083static uint64_t main_thread_id;
Yabin Cuifbfa8402015-10-30 18:37:26 -070084
Josh Gaoded557f2018-06-18 14:55:27 -070085static uint64_t fdevent_id;
86
Josh Gaofa30bf32018-03-29 16:23:43 -070087static bool run_needs_flush = false;
Josh Gao4c936392017-05-03 14:10:39 -070088static auto& run_queue_notify_fd = *new unique_fd();
89static auto& run_queue_mutex = *new std::mutex();
Josh Gaoe39ccd32018-02-23 14:37:07 -080090static auto& run_queue GUARDED_BY(run_queue_mutex) = *new std::deque<std::function<void()>>();
Josh Gao4c936392017-05-03 14:10:39 -070091
Yabin Cuib5e11412017-03-10 16:01:01 -080092void check_main_thread() {
Yabin Cuifbfa8402015-10-30 18:37:26 -070093 if (main_thread_valid) {
Josh Gao5791e212018-03-16 14:25:42 -070094 CHECK_EQ(main_thread_id, android::base::GetThreadId());
Yabin Cuifbfa8402015-10-30 18:37:26 -070095 }
96}
97
Yabin Cuib5e11412017-03-10 16:01:01 -080098void set_main_thread() {
Yabin Cuifbfa8402015-10-30 18:37:26 -070099 main_thread_valid = true;
Josh Gao5791e212018-03-16 14:25:42 -0700100 main_thread_id = android::base::GetThreadId();
Yabin Cuifbfa8402015-10-30 18:37:26 -0700101}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800102
Yabin Cuia1080162015-09-04 16:19:56 -0700103static std::string dump_fde(const fdevent* fde) {
104 std::string state;
105 if (fde->state & FDE_ACTIVE) {
106 state += "A";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800107 }
Yabin Cuia1080162015-09-04 16:19:56 -0700108 if (fde->state & FDE_PENDING) {
109 state += "P";
110 }
111 if (fde->state & FDE_CREATED) {
112 state += "C";
113 }
114 if (fde->state & FDE_READ) {
115 state += "R";
116 }
117 if (fde->state & FDE_WRITE) {
118 state += "W";
119 }
120 if (fde->state & FDE_ERROR) {
121 state += "E";
122 }
Josh Gaoded557f2018-06-18 14:55:27 -0700123 return android::base::StringPrintf("(fdevent %" PRIu64 ": fd %d %s)", fde->id, fde->fd.get(),
124 state.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800125}
126
Josh Gaoc162c712019-01-25 15:30:25 -0800127template <typename F>
128static fdevent* fdevent_create_impl(int fd, F func, void* arg) {
Josh Gao71f775a2018-05-14 11:14:33 -0700129 check_main_thread();
130 CHECK_GE(fd, 0);
131
132 fdevent* fde = new fdevent();
Josh Gaoded557f2018-06-18 14:55:27 -0700133 fde->id = fdevent_id++;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800134 fde->state = FDE_ACTIVE;
Josh Gao3b37fa22018-05-14 13:42:49 -0700135 fde->fd.reset(fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800136 fde->func = func;
137 fde->arg = arg;
Yabin Cui6dfef252015-10-06 15:10:05 -0700138 if (!set_file_block_mode(fd, false)) {
Yabin Cuic1b1f6f2015-09-15 16:27:09 -0700139 // Here is not proper to handle the error. If it fails here, some error is
140 // likely to be detected by poll(), then we can let the callback function
141 // to handle it.
Yabin Cui6dfef252015-10-06 15:10:05 -0700142 LOG(ERROR) << "failed to set non-blocking mode for fd " << fd;
Yabin Cuia1080162015-09-04 16:19:56 -0700143 }
Josh Gao3b37fa22018-05-14 13:42:49 -0700144 auto pair = g_poll_node_map.emplace(fde->fd.get(), PollNode(fde));
Yabin Cuia1080162015-09-04 16:19:56 -0700145 CHECK(pair.second) << "install existing fd " << fd;
Josh Gao71f775a2018-05-14 11:14:33 -0700146
147 fde->state |= FDE_CREATED;
148 return fde;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800149}
150
Josh Gaoc162c712019-01-25 15:30:25 -0800151fdevent* fdevent_create(int fd, fd_func func, void* arg) {
152 return fdevent_create_impl(fd, func, arg);
153}
154
155fdevent* fdevent_create(int fd, fd_func2 func, void* arg) {
156 return fdevent_create_impl(fd, func, arg);
157}
158
Josh Gao2f6c2fa2018-09-20 17:38:55 -0700159unique_fd fdevent_release(fdevent* fde) {
Yabin Cuifbfa8402015-10-30 18:37:26 -0700160 check_main_thread();
Josh Gao2f6c2fa2018-09-20 17:38:55 -0700161 if (!fde) {
162 return {};
163 }
164
Josh Gao71f775a2018-05-14 11:14:33 -0700165 if (!(fde->state & FDE_CREATED)) {
166 LOG(FATAL) << "destroying fde not created by fdevent_create(): " << dump_fde(fde);
167 }
168
Josh Gao2f6c2fa2018-09-20 17:38:55 -0700169 unique_fd result = std::move(fde->fd);
Yabin Cuia1080162015-09-04 16:19:56 -0700170 if (fde->state & FDE_ACTIVE) {
Josh Gao2f6c2fa2018-09-20 17:38:55 -0700171 g_poll_node_map.erase(result.get());
172
Yabin Cuia1080162015-09-04 16:19:56 -0700173 if (fde->state & FDE_PENDING) {
174 g_pending_list.remove(fde);
175 }
Yabin Cuia1080162015-09-04 16:19:56 -0700176 fde->state = 0;
177 fde->events = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800178 }
Josh Gao71f775a2018-05-14 11:14:33 -0700179
180 delete fde;
Josh Gao2f6c2fa2018-09-20 17:38:55 -0700181 return result;
182}
183
184void fdevent_destroy(fdevent* fde) {
185 // Release, and then let unique_fd's destructor cleanup.
186 fdevent_release(fde);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800187}
188
Yabin Cuia1080162015-09-04 16:19:56 -0700189static void fdevent_update(fdevent* fde, unsigned events) {
Josh Gao3b37fa22018-05-14 13:42:49 -0700190 auto it = g_poll_node_map.find(fde->fd.get());
Yabin Cuia1080162015-09-04 16:19:56 -0700191 CHECK(it != g_poll_node_map.end());
192 PollNode& node = it->second;
193 if (events & FDE_READ) {
194 node.pollfd.events |= POLLIN;
195 } else {
196 node.pollfd.events &= ~POLLIN;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800197 }
198
Yabin Cuia1080162015-09-04 16:19:56 -0700199 if (events & FDE_WRITE) {
200 node.pollfd.events |= POLLOUT;
201 } else {
202 node.pollfd.events &= ~POLLOUT;
203 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800204 fde->state = (fde->state & FDE_STATEMASK) | events;
Yabin Cuia1080162015-09-04 16:19:56 -0700205}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800206
Yabin Cuia1080162015-09-04 16:19:56 -0700207void fdevent_set(fdevent* fde, unsigned events) {
Yabin Cuifbfa8402015-10-30 18:37:26 -0700208 check_main_thread();
Yabin Cuia1080162015-09-04 16:19:56 -0700209 events &= FDE_EVENTMASK;
210 if ((fde->state & FDE_EVENTMASK) == events) {
211 return;
212 }
Spencer Low888a7482015-09-29 18:33:38 -0700213 CHECK(fde->state & FDE_ACTIVE);
214 fdevent_update(fde, events);
215 D("fdevent_set: %s, events = %u", dump_fde(fde).c_str(), events);
Yabin Cuia1080162015-09-04 16:19:56 -0700216
Spencer Low888a7482015-09-29 18:33:38 -0700217 if (fde->state & FDE_PENDING) {
218 // If we are pending, make sure we don't signal an event that is no longer wanted.
219 fde->events &= events;
220 if (fde->events == 0) {
221 g_pending_list.remove(fde);
222 fde->state &= ~FDE_PENDING;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800223 }
224 }
225}
226
Yabin Cuia1080162015-09-04 16:19:56 -0700227void fdevent_add(fdevent* fde, unsigned events) {
Yabin Cuifbfa8402015-10-30 18:37:26 -0700228 check_main_thread();
Josh Gao1a901182019-01-31 15:51:52 -0800229 CHECK(!(events & FDE_TIMEOUT));
Yabin Cuia1080162015-09-04 16:19:56 -0700230 fdevent_set(fde, (fde->state & FDE_EVENTMASK) | events);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800231}
232
Yabin Cuia1080162015-09-04 16:19:56 -0700233void fdevent_del(fdevent* fde, unsigned events) {
Yabin Cuifbfa8402015-10-30 18:37:26 -0700234 check_main_thread();
Josh Gao1a901182019-01-31 15:51:52 -0800235 CHECK(!(events & FDE_TIMEOUT));
Yabin Cuia1080162015-09-04 16:19:56 -0700236 fdevent_set(fde, (fde->state & FDE_EVENTMASK) & ~events);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800237}
238
Josh Gao1a901182019-01-31 15:51:52 -0800239void fdevent_set_timeout(fdevent* fde, std::optional<std::chrono::milliseconds> timeout) {
240 check_main_thread();
241 fde->timeout = timeout;
242 fde->last_active = std::chrono::steady_clock::now();
243}
244
Josh Gao3777d2e2016-02-16 17:34:53 -0800245static std::string dump_pollfds(const std::vector<adb_pollfd>& pollfds) {
Yabin Cuia1080162015-09-04 16:19:56 -0700246 std::string result;
Elliott Hughes65fe2512015-10-07 15:59:35 -0700247 for (const auto& pollfd : pollfds) {
Yabin Cuia1080162015-09-04 16:19:56 -0700248 std::string op;
249 if (pollfd.events & POLLIN) {
250 op += "R";
251 }
252 if (pollfd.events & POLLOUT) {
253 op += "W";
254 }
255 android::base::StringAppendF(&result, " %d(%s)", pollfd.fd, op.c_str());
256 }
257 return result;
258}
259
Josh Gao1a901182019-01-31 15:51:52 -0800260static std::optional<std::chrono::milliseconds> calculate_timeout() {
261 std::optional<std::chrono::milliseconds> result = std::nullopt;
262 auto now = std::chrono::steady_clock::now();
263 check_main_thread();
264
265 for (const auto& [fd, pollnode] : g_poll_node_map) {
266 UNUSED(fd);
267 auto timeout_opt = pollnode.fde->timeout;
268 if (timeout_opt) {
269 auto deadline = pollnode.fde->last_active + *timeout_opt;
270 auto time_left = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
271 if (time_left < std::chrono::milliseconds::zero()) {
272 time_left = std::chrono::milliseconds::zero();
273 }
274
275 if (!result) {
276 result = time_left;
277 } else {
278 result = std::min(*result, time_left);
279 }
280 }
281 }
282
283 return result;
284}
285
Yabin Cuia1080162015-09-04 16:19:56 -0700286static void fdevent_process() {
Josh Gao3777d2e2016-02-16 17:34:53 -0800287 std::vector<adb_pollfd> pollfds;
Elliott Hughes65fe2512015-10-07 15:59:35 -0700288 for (const auto& pair : g_poll_node_map) {
289 pollfds.push_back(pair.second.pollfd);
Yabin Cuia1080162015-09-04 16:19:56 -0700290 }
291 CHECK_GT(pollfds.size(), 0u);
292 D("poll(), pollfds = %s", dump_pollfds(pollfds).c_str());
Josh Gao39c1f4b2018-10-05 17:09:07 -0700293
Josh Gao1a901182019-01-31 15:51:52 -0800294 auto timeout = calculate_timeout();
295 int timeout_ms;
296 if (!timeout) {
297 timeout_ms = -1;
298 } else {
299 timeout_ms = timeout->count();
300 }
301
302 int ret = adb_poll(&pollfds[0], pollfds.size(), timeout_ms);
Yabin Cuia1080162015-09-04 16:19:56 -0700303 if (ret == -1) {
Yabin Cuic1b1f6f2015-09-15 16:27:09 -0700304 PLOG(ERROR) << "poll(), ret = " << ret;
305 return;
Yabin Cuia1080162015-09-04 16:19:56 -0700306 }
Josh Gao1a901182019-01-31 15:51:52 -0800307
308 auto post_poll = std::chrono::steady_clock::now();
309
Elliott Hughes65fe2512015-10-07 15:59:35 -0700310 for (const auto& pollfd : pollfds) {
Yabin Cuic1b1f6f2015-09-15 16:27:09 -0700311 if (pollfd.revents != 0) {
312 D("for fd %d, revents = %x", pollfd.fd, pollfd.revents);
313 }
Yabin Cuia1080162015-09-04 16:19:56 -0700314 unsigned events = 0;
315 if (pollfd.revents & POLLIN) {
316 events |= FDE_READ;
317 }
318 if (pollfd.revents & POLLOUT) {
319 events |= FDE_WRITE;
320 }
321 if (pollfd.revents & (POLLERR | POLLHUP | POLLNVAL)) {
322 // We fake a read, as the rest of the code assumes that errors will
323 // be detected at that point.
324 events |= FDE_READ | FDE_ERROR;
325 }
Yabin Cuiaa77e222015-09-29 12:25:33 -0700326#if defined(__linux__)
327 if (pollfd.revents & POLLRDHUP) {
328 events |= FDE_READ | FDE_ERROR;
329 }
330#endif
Josh Gao1a901182019-01-31 15:51:52 -0800331 auto it = g_poll_node_map.find(pollfd.fd);
332 CHECK(it != g_poll_node_map.end());
333 fdevent* fde = it->second.fde;
334
335 if (events == 0) {
336 // Check for timeout.
337 if (fde->timeout) {
338 auto deadline = fde->last_active + *fde->timeout;
339 if (deadline < post_poll) {
340 events |= FDE_TIMEOUT;
341 }
342 }
343 }
344
Yabin Cuia1080162015-09-04 16:19:56 -0700345 if (events != 0) {
Josh Gao3b37fa22018-05-14 13:42:49 -0700346 CHECK_EQ(fde->fd.get(), pollfd.fd);
Yabin Cuia1080162015-09-04 16:19:56 -0700347 fde->events |= events;
Josh Gao1a901182019-01-31 15:51:52 -0800348 fde->last_active = post_poll;
Yabin Cuia1080162015-09-04 16:19:56 -0700349 D("%s got events %x", dump_fde(fde).c_str(), events);
350 fde->state |= FDE_PENDING;
351 g_pending_list.push_back(fde);
352 }
353 }
354}
355
Josh Gaoc162c712019-01-25 15:30:25 -0800356template <class T>
357struct always_false : std::false_type {};
358
Josh Gao4c936392017-05-03 14:10:39 -0700359static void fdevent_call_fdfunc(fdevent* fde) {
Yabin Cuia1080162015-09-04 16:19:56 -0700360 unsigned events = fde->events;
361 fde->events = 0;
Spencer Low888a7482015-09-29 18:33:38 -0700362 CHECK(fde->state & FDE_PENDING);
Yabin Cuia1080162015-09-04 16:19:56 -0700363 fde->state &= (~FDE_PENDING);
364 D("fdevent_call_fdfunc %s", dump_fde(fde).c_str());
Josh Gaoc162c712019-01-25 15:30:25 -0800365 std::visit(
366 [&](auto&& f) {
367 using F = std::decay_t<decltype(f)>;
368 if constexpr (std::is_same_v<fd_func, F>) {
369 f(fde->fd.get(), events, fde->arg);
370 } else if constexpr (std::is_same_v<fd_func2, F>) {
371 f(fde, events, fde->arg);
372 } else {
373 static_assert(always_false<F>::value, "non-exhaustive visitor");
374 }
375 },
376 fde->func);
Yabin Cuia1080162015-09-04 16:19:56 -0700377}
378
Josh Gaoe39ccd32018-02-23 14:37:07 -0800379static void fdevent_run_flush() EXCLUDES(run_queue_mutex) {
380 // We need to be careful around reentrancy here, since a function we call can queue up another
381 // function.
382 while (true) {
383 std::function<void()> fn;
384 {
385 std::lock_guard<std::mutex> lock(run_queue_mutex);
386 if (run_queue.empty()) {
387 break;
388 }
389 fn = run_queue.front();
390 run_queue.pop_front();
391 }
392 fn();
Josh Gao4c936392017-05-03 14:10:39 -0700393 }
Josh Gao4c936392017-05-03 14:10:39 -0700394}
395
396static void fdevent_run_func(int fd, unsigned ev, void* /* userdata */) {
397 CHECK_GE(fd, 0);
398 CHECK(ev & FDE_READ);
399
400 char buf[1024];
401
402 // Empty the fd.
403 if (adb_read(fd, buf, sizeof(buf)) == -1) {
404 PLOG(FATAL) << "failed to empty run queue notify fd";
405 }
406
Josh Gaofa30bf32018-03-29 16:23:43 -0700407 // Mark that we need to flush, and then run it at the end of fdevent_loop.
408 run_needs_flush = true;
Josh Gao4c936392017-05-03 14:10:39 -0700409}
410
411static void fdevent_run_setup() {
Josh Gaoe39ccd32018-02-23 14:37:07 -0800412 {
413 std::lock_guard<std::mutex> lock(run_queue_mutex);
414 CHECK(run_queue_notify_fd.get() == -1);
415 int s[2];
416 if (adb_socketpair(s) != 0) {
417 PLOG(FATAL) << "failed to create run queue notify socketpair";
418 }
Josh Gao4c936392017-05-03 14:10:39 -0700419
Josh Gao1222abc2018-03-19 15:19:45 -0700420 if (!set_file_block_mode(s[0], false) || !set_file_block_mode(s[1], false)) {
421 PLOG(FATAL) << "failed to make run queue notify socket nonblocking";
422 }
423
Josh Gaoe39ccd32018-02-23 14:37:07 -0800424 run_queue_notify_fd.reset(s[0]);
425 fdevent* fde = fdevent_create(s[1], fdevent_run_func, nullptr);
426 CHECK(fde != nullptr);
427 fdevent_add(fde, FDE_READ);
428 }
Josh Gao4c936392017-05-03 14:10:39 -0700429
430 fdevent_run_flush();
431}
432
433void fdevent_run_on_main_thread(std::function<void()> fn) {
434 std::lock_guard<std::mutex> lock(run_queue_mutex);
435 run_queue.push_back(std::move(fn));
436
437 // run_queue_notify_fd could still be -1 if we're called before fdevent has finished setting up.
438 // In that case, rely on the setup code to flush the queue without a notification being needed.
439 if (run_queue_notify_fd != -1) {
Josh Gao1222abc2018-03-19 15:19:45 -0700440 int rc = adb_write(run_queue_notify_fd.get(), "", 1);
441
442 // It's possible that we get EAGAIN here, if lots of notifications came in while handling.
443 if (rc == 0) {
444 PLOG(FATAL) << "run queue notify fd was closed?";
445 } else if (rc == -1 && errno != EAGAIN) {
Josh Gao4c936392017-05-03 14:10:39 -0700446 PLOG(FATAL) << "failed to write to run queue notify fd";
447 }
448 }
449}
450
Josh Gao39c1f4b2018-10-05 17:09:07 -0700451static void fdevent_check_spin(uint64_t cycle) {
452 // Check to see if we're spinning because we forgot about an fdevent
453 // by keeping track of how long fdevents have been continuously pending.
454 struct SpinCheck {
455 fdevent* fde;
456 android::base::boot_clock::time_point timestamp;
457 uint64_t cycle;
458 };
459 static auto& g_continuously_pending = *new std::unordered_map<uint64_t, SpinCheck>();
460 static auto last_cycle = android::base::boot_clock::now();
461
462 auto now = android::base::boot_clock::now();
463 if (now - last_cycle > 10ms) {
464 // We're not spinning.
465 g_continuously_pending.clear();
466 last_cycle = now;
467 return;
468 }
469 last_cycle = now;
470
471 for (auto* fde : g_pending_list) {
472 auto it = g_continuously_pending.find(fde->id);
473 if (it == g_continuously_pending.end()) {
474 g_continuously_pending[fde->id] =
475 SpinCheck{.fde = fde, .timestamp = now, .cycle = cycle};
476 } else {
477 it->second.cycle = cycle;
478 }
479 }
480
481 for (auto it = g_continuously_pending.begin(); it != g_continuously_pending.end();) {
482 if (it->second.cycle != cycle) {
483 it = g_continuously_pending.erase(it);
484 } else {
485 // Use an absurdly long window, since all we really care about is
486 // getting a bugreport eventually.
487 if (now - it->second.timestamp > 300s) {
488 LOG(FATAL_WITHOUT_ABORT)
489 << "detected spin in fdevent: " << dump_fde(it->second.fde);
490#if defined(__linux__)
491 int fd = it->second.fde->fd.get();
492 std::string fd_path = android::base::StringPrintf("/proc/self/fd/%d", fd);
493 std::string path;
494 if (!android::base::Readlink(fd_path, &path)) {
495 PLOG(FATAL_WITHOUT_ABORT) << "readlink of fd " << fd << " failed";
496 }
497 LOG(FATAL_WITHOUT_ABORT) << "fd " << fd << " = " << path;
498#endif
499 abort();
500 }
501 ++it;
502 }
503 }
504}
505
Josh Gao4c936392017-05-03 14:10:39 -0700506void fdevent_loop() {
Yabin Cuifbfa8402015-10-30 18:37:26 -0700507 set_main_thread();
Josh Gao4c936392017-05-03 14:10:39 -0700508 fdevent_run_setup();
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200509
Josh Gao39c1f4b2018-10-05 17:09:07 -0700510 uint64_t cycle = 0;
Elliott Hughesaa245492015-08-03 10:38:08 -0700511 while (true) {
Josh Gao022d4472016-02-10 14:49:00 -0800512 if (terminate_loop) {
513 return;
514 }
515
Yabin Cuia1080162015-09-04 16:19:56 -0700516 D("--- --- waiting for events");
JP Abgrall408fa572011-03-16 15:57:42 -0700517
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800518 fdevent_process();
David 'Digit' Turnerf6330a22009-05-18 17:36:28 +0200519
Josh Gao39c1f4b2018-10-05 17:09:07 -0700520 fdevent_check_spin(cycle++);
521
Yabin Cuia1080162015-09-04 16:19:56 -0700522 while (!g_pending_list.empty()) {
523 fdevent* fde = g_pending_list.front();
524 g_pending_list.pop_front();
JP Abgrall408fa572011-03-16 15:57:42 -0700525 fdevent_call_fdfunc(fde);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526 }
Josh Gaofa30bf32018-03-29 16:23:43 -0700527
528 if (run_needs_flush) {
529 fdevent_run_flush();
530 run_needs_flush = false;
531 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800532 }
533}
Yabin Cuic1b1f6f2015-09-15 16:27:09 -0700534
Josh Gao022d4472016-02-10 14:49:00 -0800535void fdevent_terminate_loop() {
536 terminate_loop = true;
537}
538
Yabin Cuic1b1f6f2015-09-15 16:27:09 -0700539size_t fdevent_installed_count() {
540 return g_poll_node_map.size();
541}
542
543void fdevent_reset() {
544 g_poll_node_map.clear();
545 g_pending_list.clear();
Josh Gao4c936392017-05-03 14:10:39 -0700546
547 std::lock_guard<std::mutex> lock(run_queue_mutex);
548 run_queue_notify_fd.reset();
549 run_queue.clear();
550
Yabin Cuifbfa8402015-10-30 18:37:26 -0700551 main_thread_valid = false;
Josh Gao022d4472016-02-10 14:49:00 -0800552 terminate_loop = false;
Yabin Cuic1b1f6f2015-09-15 16:27:09 -0700553}