• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 "perfetto/base/build_config.h"
18 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
19 
20 #include <stdint.h>
21 #include <unistd.h>
22 
23 #include "perfetto/base/logging.h"
24 #include "perfetto/ext/base/event_fd.h"
25 #include "perfetto/ext/base/pipe.h"
26 #include "perfetto/ext/base/utils.h"
27 
28 #if PERFETTO_USE_EVENTFD()
29 #include <sys/eventfd.h>
30 #endif
31 
32 namespace perfetto {
33 namespace base {
34 
EventFd()35 EventFd::EventFd() {
36 #if PERFETTO_USE_EVENTFD()
37   fd_.reset(eventfd(/* start value */ 0, EFD_CLOEXEC | EFD_NONBLOCK));
38   PERFETTO_CHECK(fd_);
39 #else
40   // Make the pipe non-blocking so that we never block the waking thread (either
41   // the main thread or another one) when scheduling a wake-up.
42   Pipe pipe = Pipe::Create(Pipe::kBothNonBlock);
43   fd_ = std::move(pipe.rd);
44   write_fd_ = std::move(pipe.wr);
45 #endif  // !PERFETTO_USE_EVENTFD()
46 }
47 
48 EventFd::~EventFd() = default;
49 
Notify()50 void EventFd::Notify() {
51   const uint64_t value = 1;
52 
53 #if PERFETTO_USE_EVENTFD()
54   ssize_t ret = write(fd_.get(), &value, sizeof(value));
55 #else
56   ssize_t ret = write(write_fd_.get(), &value, sizeof(uint8_t));
57 #endif
58 
59   if (ret <= 0 && errno != EAGAIN) {
60     PERFETTO_DFATAL("write()");
61   }
62 }
63 
Clear()64 void EventFd::Clear() {
65 #if PERFETTO_USE_EVENTFD()
66   uint64_t value;
67   ssize_t ret = read(fd_.get(), &value, sizeof(value));
68 #else
69   // Drain the byte(s) written to the wake-up pipe. We can potentially read
70   // more than one byte if several wake-ups have been scheduled.
71   char buffer[16];
72   ssize_t ret = read(fd_.get(), &buffer[0], sizeof(buffer));
73 #endif
74   if (ret <= 0 && errno != EAGAIN)
75     PERFETTO_DPLOG("read()");
76 }
77 
78 }  // namespace base
79 }  // namespace perfetto
80 
81 #endif  // !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
82