Flutter Engine
timerfd.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
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 "flutter/fml/platform/linux/timerfd.h"
6 
7 #include <sys/types.h>
8 #include <unistd.h>
9 
10 #include "flutter/fml/eintr_wrapper.h"
11 #include "flutter/fml/logging.h"
12 
13 #if FML_TIMERFD_AVAILABLE == 0
14 
15 #include <asm/unistd.h>
16 #include <sys/syscall.h>
17 
18 int timerfd_create(int clockid, int flags) {
19  return syscall(__NR_timerfd_create, clockid, flags);
20 }
21 
22 int timerfd_settime(int ufc,
23  int flags,
24  const struct itimerspec* utmr,
25  struct itimerspec* otmr) {
26  return syscall(__NR_timerfd_settime, ufc, flags, utmr, otmr);
27 }
28 
29 #endif // FML_TIMERFD_AVAILABLE == 0
30 
31 namespace fml {
32 
33 #ifndef NSEC_PER_SEC
34 #define NSEC_PER_SEC 1000000000
35 #endif
36 
37 bool TimerRearm(int fd, fml::TimePoint time_point) {
38  uint64_t nano_secs = time_point.ToEpochDelta().ToNanoseconds();
39 
40  // "0" will disarm the timer, desired behavior is to immediately
41  // trigger the timer.
42  if (nano_secs < 1) {
43  nano_secs = 1;
44  }
45 
46  struct itimerspec spec = {};
47  spec.it_value.tv_sec = (time_t)(nano_secs / NSEC_PER_SEC);
48  spec.it_value.tv_nsec = nano_secs % NSEC_PER_SEC;
49  spec.it_interval = spec.it_value; // single expiry.
50 
51  int result = ::timerfd_settime(fd, TFD_TIMER_ABSTIME, &spec, nullptr);
52  if (result != 0) {
53  FML_DLOG(ERROR) << "timerfd_settime err:" << strerror(errno);
54  }
55  return result == 0;
56 }
57 
58 bool TimerDrain(int fd) {
59  // 8 bytes must be read from a signaled timer file descriptor when signaled.
60  uint64_t fire_count = 0;
61  ssize_t size = FML_HANDLE_EINTR(::read(fd, &fire_count, sizeof(uint64_t)));
62  if (size != sizeof(uint64_t)) {
63  return false;
64  }
65  return fire_count > 0;
66 }
67 
68 } // namespace fml
int timerfd_settime(int ufc, int flags, const struct itimerspec *utmr, struct itimerspec *otmr)
Definition: timerfd.cc:22
#define NSEC_PER_SEC
Definition: timerfd.cc:34
GAsyncResult * result
constexpr std::size_t size(T(&array)[N])
Definition: size.h:13
TimeDelta ToEpochDelta() const
Definition: time_point.h:47
FlutterSemanticsFlag flags
Definition: ascii_trie.cc:9
#define FML_HANDLE_EINTR(x)
Definition: eintr_wrapper.h:20
int timerfd_create(int clockid, int flags)
Definition: timerfd.cc:18
constexpr int64_t ToNanoseconds() const
Definition: time_delta.h:61
bool TimerDrain(int fd)
Definition: timerfd.cc:58
#define FML_DLOG(severity)
Definition: logging.h:85
bool TimerRearm(int fd, fml::TimePoint time_point)
Rearms the timer to expire at the given time point.
Definition: timerfd.cc:37
#define TFD_TIMER_ABSTIME
Definition: timerfd.h:29