• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/message_loop/message_pump_libevent.h"
6 
7 #include <errno.h>
8 #include <unistd.h>
9 
10 #include <memory>
11 #include <utility>
12 
13 #include "base/auto_reset.h"
14 #include "base/compiler_specific.h"
15 #include "base/feature_list.h"
16 #include "base/files/file_util.h"
17 #include "base/logging.h"
18 #include "base/notreached.h"
19 #include "base/posix/eintr_wrapper.h"
20 #include "base/time/time.h"
21 #include "base/trace_event/base_tracing.h"
22 #include "build/build_config.h"
23 #include "third_party/libevent/event.h"
24 
25 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
26 #include "base/message_loop/message_pump_epoll.h"
27 #endif
28 
29 // Lifecycle of struct event
30 // Libevent uses two main data structures:
31 // struct event_base (of which there is one per message pump), and
32 // struct event (of which there is roughly one per socket).
33 // The socket's struct event is created in
34 // MessagePumpLibevent::WatchFileDescriptor(),
35 // is owned by the FdWatchController, and is destroyed in
36 // StopWatchingFileDescriptor().
37 // It is moved into and out of lists in struct event_base by
38 // the libevent functions event_add() and event_del().
39 
40 namespace base {
41 
42 namespace {
43 
44 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
45 bool g_use_epoll = false;
46 
47 BASE_FEATURE(kMessagePumpEpoll, "MessagePumpEpoll", FEATURE_ENABLED_BY_DEFAULT);
48 #endif
49 
50 }  // namespace
51 
FdWatchController(const Location & from_here)52 MessagePumpLibevent::FdWatchController::FdWatchController(
53     const Location& from_here)
54     : FdWatchControllerInterface(from_here) {}
55 
~FdWatchController()56 MessagePumpLibevent::FdWatchController::~FdWatchController() {
57   CHECK(StopWatchingFileDescriptor());
58   if (was_destroyed_) {
59     DCHECK(!*was_destroyed_);
60     *was_destroyed_ = true;
61   }
62 }
63 
StopWatchingFileDescriptor()64 bool MessagePumpLibevent::FdWatchController::StopWatchingFileDescriptor() {
65   watcher_ = nullptr;
66 
67   std::unique_ptr<event> e = ReleaseEvent();
68   if (e) {
69     // event_del() is a no-op if the event isn't active.
70     int rv = event_del(e.get());
71     libevent_pump_ = nullptr;
72     return (rv == 0);
73   }
74 
75 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
76   if (epoll_interest_ && epoll_pump_) {
77     epoll_pump_->UnregisterInterest(epoll_interest_);
78     epoll_interest_.reset();
79     epoll_pump_.reset();
80   }
81 #endif
82 
83   return true;
84 }
85 
Init(std::unique_ptr<event> e)86 void MessagePumpLibevent::FdWatchController::Init(std::unique_ptr<event> e) {
87   DCHECK(e);
88   DCHECK(!event_);
89 
90   event_ = std::move(e);
91 }
92 
ReleaseEvent()93 std::unique_ptr<event> MessagePumpLibevent::FdWatchController::ReleaseEvent() {
94   return std::move(event_);
95 }
96 
OnFileCanReadWithoutBlocking(int fd,MessagePumpLibevent * pump)97 void MessagePumpLibevent::FdWatchController::OnFileCanReadWithoutBlocking(
98     int fd,
99     MessagePumpLibevent* pump) {
100   // Since OnFileCanWriteWithoutBlocking() gets called first, it can stop
101   // watching the file descriptor.
102   if (!watcher_)
103     return;
104   watcher_->OnFileCanReadWithoutBlocking(fd);
105 }
106 
OnFileCanWriteWithoutBlocking(int fd,MessagePumpLibevent * pump)107 void MessagePumpLibevent::FdWatchController::OnFileCanWriteWithoutBlocking(
108     int fd,
109     MessagePumpLibevent* pump) {
110   DCHECK(watcher_);
111   watcher_->OnFileCanWriteWithoutBlocking(fd);
112 }
113 
114 const scoped_refptr<MessagePumpLibevent::EpollInterest>&
AssignEpollInterest(const EpollInterestParams & params)115 MessagePumpLibevent::FdWatchController::AssignEpollInterest(
116     const EpollInterestParams& params) {
117   epoll_interest_ = MakeRefCounted<EpollInterest>(this, params);
118   return epoll_interest_;
119 }
120 
OnFdReadable()121 void MessagePumpLibevent::FdWatchController::OnFdReadable() {
122   if (!watcher_) {
123     // When a watcher is watching both read and write and both are possible, the
124     // pump will call OnFdWritable() first, followed by OnFdReadable(). But
125     // OnFdWritable() may stop or destroy the watch. If the watch is destroyed,
126     // the pump will not call OnFdReadable() at all, but if it's merely stopped,
127     // OnFdReadable() will be called while `watcher_` is  null. In this case we
128     // don't actually want to call the client.
129     return;
130   }
131   watcher_->OnFileCanReadWithoutBlocking(epoll_interest_->params().fd);
132 }
133 
OnFdWritable()134 void MessagePumpLibevent::FdWatchController::OnFdWritable() {
135   DCHECK(watcher_);
136   watcher_->OnFileCanWriteWithoutBlocking(epoll_interest_->params().fd);
137 }
138 
MessagePumpLibevent()139 MessagePumpLibevent::MessagePumpLibevent() {
140 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
141   if (g_use_epoll) {
142     epoll_pump_ = std::make_unique<MessagePumpEpoll>();
143     return;
144   }
145 #endif
146 
147   if (!Init())
148     NOTREACHED();
149   DCHECK_NE(wakeup_pipe_in_, -1);
150   DCHECK_NE(wakeup_pipe_out_, -1);
151   DCHECK(wakeup_event_);
152 }
153 
154 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
MessagePumpLibevent(decltype(kUseEpoll) )155 MessagePumpLibevent::MessagePumpLibevent(decltype(kUseEpoll))
156     : epoll_pump_(std::make_unique<MessagePumpEpoll>()) {}
157 #endif
158 
~MessagePumpLibevent()159 MessagePumpLibevent::~MessagePumpLibevent() {
160 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
161   const bool using_libevent = !epoll_pump_;
162 #else
163   const bool using_libevent = true;
164 #endif
165 
166   DCHECK(event_base_);
167   if (using_libevent) {
168     DCHECK(wakeup_event_);
169     event_del(wakeup_event_.get());
170     wakeup_event_.reset();
171     if (wakeup_pipe_in_ >= 0) {
172       if (IGNORE_EINTR(close(wakeup_pipe_in_)) < 0)
173         DPLOG(ERROR) << "close";
174     }
175     if (wakeup_pipe_out_ >= 0) {
176       if (IGNORE_EINTR(close(wakeup_pipe_out_)) < 0)
177         DPLOG(ERROR) << "close";
178     }
179   }
180   event_base_.reset();
181 }
182 
183 // Must be called early in process startup, but after FeatureList
184 // initialization. This allows MessagePumpLibevent to query and cache the
185 // enabled state of any relevant features.
186 // static
InitializeFeatures()187 void MessagePumpLibevent::InitializeFeatures() {
188 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
189   g_use_epoll = FeatureList::IsEnabled(kMessagePumpEpoll);
190 #endif
191 }
192 
WatchFileDescriptor(int fd,bool persistent,int mode,FdWatchController * controller,FdWatcher * delegate)193 bool MessagePumpLibevent::WatchFileDescriptor(int fd,
194                                               bool persistent,
195                                               int mode,
196                                               FdWatchController* controller,
197                                               FdWatcher* delegate) {
198 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
199   if (epoll_pump_) {
200     return epoll_pump_->WatchFileDescriptor(fd, persistent, mode, controller,
201                                             delegate);
202   }
203 #endif
204 
205   TRACE_EVENT("base", "MessagePumpLibevent::WatchFileDescriptor", "fd", fd,
206               "persistent", persistent, "watch_read", mode & WATCH_READ,
207               "watch_write", mode & WATCH_WRITE);
208   DCHECK_GE(fd, 0);
209   DCHECK(controller);
210   DCHECK(delegate);
211   DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
212   // WatchFileDescriptor should be called on the pump thread. It is not
213   // threadsafe, and your watcher may never be registered.
214   DCHECK(watch_file_descriptor_caller_checker_.CalledOnValidThread());
215 
216   short event_mask = persistent ? EV_PERSIST : 0;
217   if (mode & WATCH_READ) {
218     event_mask |= EV_READ;
219   }
220   if (mode & WATCH_WRITE) {
221     event_mask |= EV_WRITE;
222   }
223 
224   std::unique_ptr<event> evt(controller->ReleaseEvent());
225   if (!evt) {
226     // Ownership is transferred to the controller.
227     evt = std::make_unique<event>();
228   } else {
229     // Make sure we don't pick up any funky internal libevent masks.
230     int old_interest_mask = evt->ev_events & (EV_READ | EV_WRITE | EV_PERSIST);
231 
232     // Combine old/new event masks.
233     event_mask |= old_interest_mask;
234 
235     // Must disarm the event before we can reuse it.
236     event_del(evt.get());
237 
238     // It's illegal to use this function to listen on 2 separate fds with the
239     // same |controller|.
240     if (EVENT_FD(evt.get()) != fd) {
241       NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd;
242       return false;
243     }
244   }
245 
246   // Set current interest mask and message pump for this event.
247   event_set(evt.get(), fd, event_mask, OnLibeventNotification, controller);
248 
249   // Tell libevent which message pump this socket will belong to when we add it.
250   if (event_base_set(event_base_.get(), evt.get())) {
251     DPLOG(ERROR) << "event_base_set(fd=" << EVENT_FD(evt.get()) << ")";
252     return false;
253   }
254 
255   // Add this socket to the list of monitored sockets.
256   if (event_add(evt.get(), nullptr)) {
257     DPLOG(ERROR) << "event_add failed(fd=" << EVENT_FD(evt.get()) << ")";
258     return false;
259   }
260 
261   controller->Init(std::move(evt));
262   controller->set_watcher(delegate);
263   controller->set_libevent_pump(this);
264   return true;
265 }
266 
267 // Tell libevent to break out of inner loop.
timer_callback(int fd,short events,void * context)268 static void timer_callback(int fd, short events, void* context) {
269   event_base_loopbreak((struct event_base*)context);
270 }
271 
272 // Reentrant!
Run(Delegate * delegate)273 void MessagePumpLibevent::Run(Delegate* delegate) {
274 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
275   if (epoll_pump_) {
276     epoll_pump_->Run(delegate);
277     return;
278   }
279 #endif
280 
281   RunState run_state(delegate);
282   AutoReset<RunState*> auto_reset_run_state(&run_state_, &run_state);
283 
284   // event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
285   // Instead, make our own timer and reuse it on each call to event_base_loop().
286   std::unique_ptr<event> timer_event(new event);
287 
288   for (;;) {
289     // Do some work and see if the next task is ready right away.
290     Delegate::NextWorkInfo next_work_info = delegate->DoWork();
291     bool immediate_work_available = next_work_info.is_immediate();
292 
293     if (run_state.should_quit)
294       break;
295 
296     // Process native events if any are ready. Do not block waiting for more. Do
297     // not instantiate a ScopedDoWorkItem for this call as:
298     //  - This most often ends up calling OnLibeventNotification() below which
299     //    already instantiates a ScopedDoWorkItem (and doing so twice would
300     //    incorrectly appear as nested work).
301     //  - "ThreadController active" is already up per the above DoWork() so this
302     //    would only be about detecting #work-in-work-implies-nested
303     //    (ref. thread_controller.h).
304     //  - This can result in the same work as the
305     //    event_base_loop(event_base_, EVLOOP_ONCE) call at the end of this
306     //    method and that call definitely can't be in a ScopedDoWorkItem as
307     //    it includes sleep.
308     //  - The only downside is that, if a native work item other than
309     //    OnLibeventNotification() did enter a nested loop from here, it
310     //    wouldn't be labeled as such in tracing by "ThreadController active".
311     //    Contact gab@/scheduler-dev@ if a problematic trace emerges.
312     event_base_loop(event_base_.get(), EVLOOP_NONBLOCK);
313 
314     bool attempt_more_work = immediate_work_available || processed_io_events_;
315     processed_io_events_ = false;
316 
317     if (run_state.should_quit)
318       break;
319 
320     if (attempt_more_work)
321       continue;
322 
323     attempt_more_work = delegate->DoIdleWork();
324 
325     if (run_state.should_quit)
326       break;
327 
328     if (attempt_more_work)
329       continue;
330 
331     bool did_set_timer = false;
332 
333     // If there is delayed work.
334     DCHECK(!next_work_info.delayed_run_time.is_null());
335     if (!next_work_info.delayed_run_time.is_max()) {
336       const TimeDelta delay = next_work_info.remaining_delay();
337 
338       // Setup a timer to break out of the event loop at the right time.
339       struct timeval poll_tv;
340       poll_tv.tv_sec = static_cast<time_t>(delay.InSeconds());
341       poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
342       event_set(timer_event.get(), -1, 0, timer_callback, event_base_.get());
343       event_base_set(event_base_.get(), timer_event.get());
344       event_add(timer_event.get(), &poll_tv);
345 
346       did_set_timer = true;
347     }
348 
349     // Block waiting for events and process all available upon waking up. This
350     // is conditionally interrupted to look for more work if we are aware of a
351     // delayed task that will need servicing.
352     delegate->BeforeWait();
353     event_base_loop(event_base_.get(), EVLOOP_ONCE);
354 
355     // We previously setup a timer to break out the event loop to look for more
356     // work. Now that we're here delete the event.
357     if (did_set_timer) {
358       event_del(timer_event.get());
359     }
360 
361     if (run_state.should_quit)
362       break;
363   }
364 }
365 
Quit()366 void MessagePumpLibevent::Quit() {
367 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
368   if (epoll_pump_) {
369     epoll_pump_->Quit();
370     return;
371   }
372 #endif
373 
374   DCHECK(run_state_) << "Quit was called outside of Run!";
375   // Tell both libevent and Run that they should break out of their loops.
376   run_state_->should_quit = true;
377   ScheduleWork();
378 }
379 
ScheduleWork()380 void MessagePumpLibevent::ScheduleWork() {
381 #if BUILDFLAG(ENABLE_MESSAGE_PUMP_EPOLL)
382   if (epoll_pump_) {
383     epoll_pump_->ScheduleWork();
384     return;
385   }
386 #endif
387 
388   // Tell libevent (in a threadsafe way) that it should break out of its loop.
389   char buf = 0;
390   long nwrite = HANDLE_EINTR(write(wakeup_pipe_in_, &buf, 1));
391   DPCHECK(nwrite == 1 || errno == EAGAIN) << "nwrite:" << nwrite;
392 }
393 
ScheduleDelayedWork(const Delegate::NextWorkInfo & next_work_info)394 void MessagePumpLibevent::ScheduleDelayedWork(
395     const Delegate::NextWorkInfo& next_work_info) {
396   // When using libevent we know that we can't be blocked on Run()'s
397   // `timer_event` right now since this method can only be called on the same
398   // thread as Run(). When using epoll, the pump clearly must be in between
399   // waits if we're here. In either case, any scheduled work will be seen prior
400   // to the next libevent loop or epoll wait, so there's nothing to do here.
401 }
402 
Init()403 bool MessagePumpLibevent::Init() {
404   int fds[2];
405   if (!CreateLocalNonBlockingPipe(fds)) {
406     DPLOG(ERROR) << "pipe creation failed";
407     return false;
408   }
409   wakeup_pipe_out_ = fds[0];
410   wakeup_pipe_in_ = fds[1];
411 
412   wakeup_event_ = std::make_unique<event>();
413   event_set(wakeup_event_.get(), wakeup_pipe_out_, EV_READ | EV_PERSIST,
414             OnWakeup, this);
415   event_base_set(event_base_.get(), wakeup_event_.get());
416 
417   if (event_add(wakeup_event_.get(), nullptr))
418     return false;
419   return true;
420 }
421 
422 // static
OnLibeventNotification(int fd,short flags,void * context)423 void MessagePumpLibevent::OnLibeventNotification(int fd,
424                                                  short flags,
425                                                  void* context) {
426   FdWatchController* controller = static_cast<FdWatchController*>(context);
427   DCHECK(controller);
428 
429   MessagePumpLibevent* pump = controller->libevent_pump();
430   pump->processed_io_events_ = true;
431 
432   // Make the MessagePumpDelegate aware of this other form of "DoWork". Skip if
433   // OnLibeventNotification is called outside of Run() (e.g. in unit tests).
434   Delegate::ScopedDoWorkItem scoped_do_work_item;
435   if (pump->run_state_)
436     scoped_do_work_item = pump->run_state_->delegate->BeginWorkItem();
437 
438   // Trace events must begin after the above BeginWorkItem() so that the
439   // ensuing "ThreadController active" outscopes all the events under it.
440   TRACE_EVENT("toplevel", "OnLibevent", "controller_created_from",
441               controller->created_from_location(), "fd", fd, "flags", flags,
442               "context", context);
443   TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION heap_profiler_scope(
444       controller->created_from_location().file_name());
445 
446   if ((flags & (EV_READ | EV_WRITE)) == (EV_READ | EV_WRITE)) {
447     // Both callbacks will be called. It is necessary to check that |controller|
448     // is not destroyed.
449     bool controller_was_destroyed = false;
450     controller->was_destroyed_ = &controller_was_destroyed;
451     controller->OnFileCanWriteWithoutBlocking(fd, pump);
452     if (!controller_was_destroyed)
453       controller->OnFileCanReadWithoutBlocking(fd, pump);
454     if (!controller_was_destroyed)
455       controller->was_destroyed_ = nullptr;
456   } else if (flags & EV_WRITE) {
457     controller->OnFileCanWriteWithoutBlocking(fd, pump);
458   } else if (flags & EV_READ) {
459     controller->OnFileCanReadWithoutBlocking(fd, pump);
460   }
461 }
462 
463 // Called if a byte is received on the wakeup pipe.
464 // static
OnWakeup(int socket,short flags,void * context)465 void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
466   TRACE_EVENT(TRACE_DISABLED_BY_DEFAULT("base"),
467               "MessagePumpLibevent::OnWakeup", "socket", socket, "flags", flags,
468               "context", context);
469   MessagePumpLibevent* that = static_cast<MessagePumpLibevent*>(context);
470   DCHECK(that->wakeup_pipe_out_ == socket);
471 
472   // Remove and discard the wakeup byte.
473   char buf;
474   long nread = HANDLE_EINTR(read(socket, &buf, 1));
475   DCHECK_EQ(nread, 1);
476   that->processed_io_events_ = true;
477   // Tell libevent to break out of inner loop.
478   event_base_loopbreak(that->event_base_.get());
479 }
480 
EpollInterest(FdWatchController * controller,const EpollInterestParams & params)481 MessagePumpLibevent::EpollInterest::EpollInterest(
482     FdWatchController* controller,
483     const EpollInterestParams& params)
484     : controller_(controller), params_(params) {}
485 
486 MessagePumpLibevent::EpollInterest::~EpollInterest() = default;
487 
488 }  // namespace base
489