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 #ifndef INCLUDE_PERFETTO_EXT_BASE_EVENT_FD_H_
18 #define INCLUDE_PERFETTO_EXT_BASE_EVENT_FD_H_
19 
20 #include "perfetto/base/build_config.h"
21 #include "perfetto/base/platform_handle.h"
22 #include "perfetto/ext/base/scoped_file.h"
23 
24 namespace perfetto {
25 namespace base {
26 
27 // A waitable event that can be used with poll/select.
28 // This is really a wrapper around eventfd_create with a pipe-based fallback
29 // for other platforms where eventfd is not supported.
30 class EventFd {
31  public:
32   EventFd();
33   ~EventFd();
34   EventFd(EventFd&&) noexcept = default;
35   EventFd& operator=(EventFd&&) = default;
36 
37   // The non-blocking file descriptor that can be polled to wait for the event.
fd()38   PlatformHandle fd() const { return event_handle_.get(); }
39 
40   // Can be called from any thread.
41   void Notify();
42 
43   // Can be called from any thread. If more Notify() are queued a Clear() call
44   // can clear all of them (up to 16 per call).
45   void Clear();
46 
47  private:
48   // The eventfd, when eventfd is supported, otherwise this is the read end of
49   // the pipe for fallback mode.
50   ScopedPlatformHandle event_handle_;
51 
52 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) &&   \
53     !PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && \
54     !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
55   // On Mac and other non-Linux UNIX platforms a pipe-based fallback is used.
56   // The write end of the wakeup pipe.
57   ScopedFile write_fd_;
58 #endif
59 };
60 
61 }  // namespace base
62 }  // namespace perfetto
63 
64 #endif  // INCLUDE_PERFETTO_EXT_BASE_EVENT_FD_H_
65