• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 "IOEventLoop.h"
18 
19 #include <event2/event.h>
20 #include <fcntl.h>
21 
22 #include <android-base/logging.h>
23 
24 namespace simpleperf {
25 
26 struct IOEvent {
27   IOEventLoop* loop;
28   event* e;
29   timeval timeout;
30   std::function<bool()> callback;
31   bool enabled;
32 
IOEventsimpleperf::IOEvent33   IOEvent(IOEventLoop* loop, const std::function<bool()>& callback)
34       : loop(loop), e(nullptr), timeout({}), callback(callback), enabled(false) {}
35 
~IOEventsimpleperf::IOEvent36   ~IOEvent() {
37     if (e != nullptr) {
38       event_free(e);
39     }
40   }
41 };
42 
IOEventLoop()43 IOEventLoop::IOEventLoop()
44     : ebase_(nullptr), has_error_(false), use_precise_timer_(false), in_loop_(false) {}
45 
~IOEventLoop()46 IOEventLoop::~IOEventLoop() {
47   events_.clear();
48   if (ebase_ != nullptr) {
49     event_base_free(ebase_);
50   }
51 }
52 
UsePreciseTimer()53 bool IOEventLoop::UsePreciseTimer() {
54   if (ebase_ != nullptr) {
55     return false;  // Too late to set the flag.
56   }
57   use_precise_timer_ = true;
58   return true;
59 }
60 
EnsureInit()61 bool IOEventLoop::EnsureInit() {
62   if (ebase_ == nullptr) {
63     event_config* cfg = event_config_new();
64     if (cfg != nullptr) {
65       if (use_precise_timer_) {
66         event_config_set_flag(cfg, EVENT_BASE_FLAG_PRECISE_TIMER);
67       }
68       if (event_config_avoid_method(cfg, "epoll") != 0) {
69         LOG(ERROR) << "event_config_avoid_method";
70         return false;
71       }
72       ebase_ = event_base_new_with_config(cfg);
73       // perf event files support reporting available data via poll methods. However, it doesn't
74       // work well with epoll. Because perf_poll() in kernel/events/core.c uses a report and reset
75       // way to report poll events. If perf_poll() is called twice, it may return POLLIN for the
76       // first time, and no events for the second time. And epoll may call perf_poll() more than
77       // once to confirm events. A failed situation is below:
78       // When profiling SimpleperfExampleOfKotlin on Pixel device with `-g --duration 10`, the
79       // kernel fills up the buffer before we call epoll_ctl(EPOLL_CTL_ADD). Then the POLLIN event
80       // is returned when calling epoll_ctl(), while no events are returned when calling
81       // epoll_wait(). As a result, simpleperf doesn't receive any poll wakeup events.
82       if (strcmp(event_base_get_method(ebase_), "poll") != 0) {
83         LOG(ERROR) << "event_base_get_method isn't poll: " << event_base_get_method(ebase_);
84         return false;
85       }
86       event_config_free(cfg);
87       if (event_base_priority_init(ebase_, 2) != 0) {
88         LOG(ERROR) << "event_base_priority_init failed";
89         return false;
90       }
91     }
92     if (ebase_ == nullptr) {
93       LOG(ERROR) << "failed to create event_base";
94       return false;
95     }
96   }
97   return true;
98 }
99 
EventCallbackFn(int,int16_t,void * arg)100 void IOEventLoop::EventCallbackFn(int, int16_t, void* arg) {
101   IOEvent* e = static_cast<IOEvent*>(arg);
102   if (!e->callback()) {
103     e->loop->has_error_ = true;
104     e->loop->ExitLoop();
105   }
106 }
107 
MakeFdNonBlocking(int fd)108 static bool MakeFdNonBlocking(int fd) {
109   int flags = fcntl(fd, F_GETFL, 0);
110   if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
111     PLOG(ERROR) << "fcntl() failed";
112     return false;
113   }
114   return true;
115 }
116 
AddReadEvent(int fd,const std::function<bool ()> & callback,IOEventPriority priority)117 IOEventRef IOEventLoop::AddReadEvent(int fd, const std::function<bool()>& callback,
118                                      IOEventPriority priority) {
119   if (!MakeFdNonBlocking(fd)) {
120     return nullptr;
121   }
122   return AddEvent(fd, EV_READ | EV_PERSIST, nullptr, callback, priority);
123 }
124 
AddWriteEvent(int fd,const std::function<bool ()> & callback,IOEventPriority priority)125 IOEventRef IOEventLoop::AddWriteEvent(int fd, const std::function<bool()>& callback,
126                                       IOEventPriority priority) {
127   if (!MakeFdNonBlocking(fd)) {
128     return nullptr;
129   }
130   return AddEvent(fd, EV_WRITE | EV_PERSIST, nullptr, callback, priority);
131 }
132 
AddSignalEvent(int sig,const std::function<bool ()> & callback,IOEventPriority priority)133 bool IOEventLoop::AddSignalEvent(int sig, const std::function<bool()>& callback,
134                                  IOEventPriority priority) {
135   return AddEvent(sig, EV_SIGNAL | EV_PERSIST, nullptr, callback, priority) != nullptr;
136 }
137 
AddSignalEvents(std::vector<int> sigs,const std::function<bool ()> & callback,IOEventPriority priority)138 bool IOEventLoop::AddSignalEvents(std::vector<int> sigs, const std::function<bool()>& callback,
139                                   IOEventPriority priority) {
140   for (auto sig : sigs) {
141     if (!AddSignalEvent(sig, callback, priority)) {
142       return false;
143     }
144   }
145   return true;
146 }
147 
AddPeriodicEvent(timeval duration,const std::function<bool ()> & callback,IOEventPriority priority)148 IOEventRef IOEventLoop::AddPeriodicEvent(timeval duration, const std::function<bool()>& callback,
149                                          IOEventPriority priority) {
150   return AddEvent(-1, EV_PERSIST, &duration, callback, priority);
151 }
152 
AddEvent(int fd_or_sig,int16_t events,timeval * timeout,const std::function<bool ()> & callback,IOEventPriority priority)153 IOEventRef IOEventLoop::AddEvent(int fd_or_sig, int16_t events, timeval* timeout,
154                                  const std::function<bool()>& callback, IOEventPriority priority) {
155   if (!EnsureInit()) {
156     return nullptr;
157   }
158   std::unique_ptr<IOEvent> e(new IOEvent(this, callback));
159   e->e = event_new(ebase_, fd_or_sig, events, EventCallbackFn, e.get());
160   if (e->e == nullptr) {
161     LOG(ERROR) << "event_new() failed";
162     return nullptr;
163   }
164   event_priority_set(e->e, priority);
165   if (event_add(e->e, timeout) != 0) {
166     LOG(ERROR) << "event_add() failed";
167     return nullptr;
168   }
169   if (timeout != nullptr) {
170     e->timeout = *timeout;
171   }
172   e->enabled = true;
173   events_.push_back(std::move(e));
174   return events_.back().get();
175 }
176 
RunLoop()177 bool IOEventLoop::RunLoop() {
178   in_loop_ = true;
179   if (event_base_dispatch(ebase_) == -1) {
180     LOG(ERROR) << "event_base_dispatch() failed";
181     in_loop_ = false;
182     return false;
183   }
184   if (has_error_) {
185     return false;
186   }
187   return true;
188 }
189 
ExitLoop()190 bool IOEventLoop::ExitLoop() {
191   if (in_loop_) {
192     if (event_base_loopbreak(ebase_) == -1) {
193       LOG(ERROR) << "event_base_loopbreak() failed";
194       return false;
195     }
196     in_loop_ = false;
197   }
198   return true;
199 }
200 
DisableEvent(IOEventRef ref)201 bool IOEventLoop::DisableEvent(IOEventRef ref) {
202   if (ref->enabled) {
203     if (event_del(ref->e) != 0) {
204       LOG(ERROR) << "event_del() failed";
205       return false;
206     }
207     ref->enabled = false;
208   }
209   return true;
210 }
211 
EnableEvent(IOEventRef ref)212 bool IOEventLoop::EnableEvent(IOEventRef ref) {
213   if (!ref->enabled) {
214     timeval* timeout =
215         (ref->timeout.tv_sec != 0 || ref->timeout.tv_usec != 0) ? &ref->timeout : nullptr;
216     if (event_add(ref->e, timeout) != 0) {
217       LOG(ERROR) << "event_add() failed";
218       return false;
219     }
220     ref->enabled = true;
221   }
222   return true;
223 }
224 
DelEvent(IOEventRef ref)225 bool IOEventLoop::DelEvent(IOEventRef ref) {
226   DisableEvent(ref);
227   IOEventLoop* loop = ref->loop;
228   for (auto it = loop->events_.begin(); it != loop->events_.end(); ++it) {
229     if (it->get() == ref) {
230       loop->events_.erase(it);
231       break;
232     }
233   }
234   return true;
235 }
236 
237 }  // namespace simpleperf
238