blob: 4bca09e6d5cbf91dda4851bc20fb5c6a8a8050d1 [file] [log] [blame]
Mark Salyzyn6c6ec722015-10-24 16:20:18 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "epoll.h"
18
19#include <sys/epoll.h>
20
21#include <chrono>
22#include <functional>
23#include <map>
24
25namespace android {
26namespace init {
27
28Epoll::Epoll() {}
29
30Result<Success> Epoll::Open() {
31 if (epoll_fd_ >= 0) return Success();
32 epoll_fd_.reset(epoll_create1(EPOLL_CLOEXEC));
33
34 if (epoll_fd_ == -1) {
35 return ErrnoError() << "epoll_create1 failed";
36 }
37 return Success();
38}
39
40Result<Success> Epoll::RegisterHandler(int fd, std::function<void()> handler) {
41 auto [it, inserted] = epoll_handlers_.emplace(fd, std::move(handler));
42 if (!inserted) {
43 return Error() << "Cannot specify two epoll handlers for a given FD";
44 }
45 epoll_event ev;
46 ev.events = EPOLLIN;
47 // std::map's iterators do not get invalidated until erased, so we use the
48 // pointer to the std::function in the map directly for epoll_ctl.
49 ev.data.ptr = reinterpret_cast<void*>(&it->second);
50 if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &ev) == -1) {
51 Result<Success> result = ErrnoError() << "epoll_ctl failed to add fd";
52 epoll_handlers_.erase(fd);
53 return result;
54 }
55 return Success();
56}
57
58Result<Success> Epoll::UnregisterHandler(int fd) {
59 if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, nullptr) == -1) {
60 return ErrnoError() << "epoll_ctl failed to remove fd";
61 }
62 if (epoll_handlers_.erase(fd) != 1) {
63 return Error() << "Attempting to remove epoll handler for FD without an existing handler";
64 }
65 return Success();
66}
67
68Result<Success> Epoll::Wait(std::optional<std::chrono::milliseconds> timeout) {
69 int timeout_ms = -1;
70 if (timeout && timeout->count() < INT_MAX) {
71 timeout_ms = timeout->count();
72 }
73 epoll_event ev;
74 auto nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd_, &ev, 1, timeout_ms));
75 if (nr == -1) {
76 return ErrnoError() << "epoll_wait failed";
77 } else if (nr == 1) {
78 std::invoke(*reinterpret_cast<std::function<void()>*>(ev.data.ptr));
79 }
80 return Success();
81}
82
83} // namespace init
84} // namespace android