1 /*
2 * Copyright (C) 2022 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 "host/commands/cvd/epoll_loop.h"
18
19 #include <android-base/errors.h>
20
21 #include "common/libs/fs/epoll.h"
22 #include "common/libs/fs/shared_fd.h"
23 #include "common/libs/utils/contains.h"
24 #include "common/libs/utils/result.h"
25
26 namespace cuttlefish {
27
EpollPool()28 EpollPool::EpollPool() {
29 auto epoll = Epoll::Create();
30 if (!epoll.ok()) {
31 LOG(ERROR) << epoll.error().Message();
32 LOG(DEBUG) << epoll.error().Trace();
33 abort();
34 }
35 epoll_ = std::move(*epoll);
36 }
37
Register(SharedFD fd,uint32_t events,EpollCallback callback)38 Result<void> EpollPool::Register(SharedFD fd, uint32_t events,
39 EpollCallback callback) {
40 std::lock_guard callbacks_lock(callbacks_mutex_);
41 CF_EXPECT(!Contains(callbacks_, fd), "Already have a callback created");
42 CF_EXPECT(epoll_.AddOrModify(fd, events | EPOLLONESHOT));
43 callbacks_[fd] = std::move(callback);
44 return {};
45 }
46
HandleEvent()47 Result<void> EpollPool::HandleEvent() {
48 auto event = CF_EXPECT(epoll_.Wait());
49 if (!event) {
50 return {};
51 }
52 EpollCallback callback;
53 {
54 std::lock_guard callbacks_lock(callbacks_mutex_);
55 auto it = callbacks_.find(event->fd);
56 CF_EXPECT(it != callbacks_.end(), "Could not find event callback");
57 callback = std::move(it->second);
58 callbacks_.erase(it);
59 }
60 CF_EXPECT(callback(*event));
61 return {};
62 }
63
Remove(SharedFD fd)64 Result<void> EpollPool::Remove(SharedFD fd) {
65 std::lock_guard callbacks_lock(callbacks_mutex_);
66 CF_EXPECT(epoll_.Delete(fd), "No callback registered with epoll");
67 callbacks_.erase(fd);
68 return {};
69 }
70
EpollLoopComponent()71 fruit::Component<EpollPool> EpollLoopComponent() {
72 return fruit::createComponent();
73 }
74
75 } // namespace cuttlefish
76