aboutsummaryrefslogtreecommitdiff
path: root/gd/os/linux_generic/repeating_alarm.cc
blob: 79cda6da1deaef5a08913743eb1438e30b07d7d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * Copyright 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "os/repeating_alarm.h"

#include <sys/timerfd.h>
#include <cstring>
#include <unistd.h>

#include "common/bind.h"
#include "os/log.h"
#include "os/utils.h"

#ifdef OS_ANDROID
#define ALARM_CLOCK CLOCK_BOOTTIME_ALARM
#else
#define ALARM_CLOCK CLOCK_BOOTTIME
#endif

namespace bluetooth {
namespace os {

RepeatingAlarm::RepeatingAlarm(Handler* handler) : handler_(handler), fd_(timerfd_create(ALARM_CLOCK, 0)) {
  ASSERT(fd_ != -1);

  token_ = handler_->thread_->GetReactor()->Register(
      fd_, common::Bind(&RepeatingAlarm::on_fire, common::Unretained(this)), common::Closure());
}

RepeatingAlarm::~RepeatingAlarm() {
  handler_->thread_->GetReactor()->Unregister(token_);

  int close_status;
  RUN_NO_INTR(close_status = close(fd_));
  ASSERT(close_status != -1);
}

void RepeatingAlarm::Schedule(Closure task, std::chrono::milliseconds period) {
  std::lock_guard<std::mutex> lock(mutex_);
  long period_ms = period.count();
  itimerspec timer_itimerspec{
    {period_ms / 1000, period_ms % 1000 * 1000000},
    {period_ms / 1000, period_ms % 1000 * 1000000}
  };
  int result = timerfd_settime(fd_, 0, &timer_itimerspec, nullptr);
  ASSERT(result == 0);

  task_ = std::move(task);
}

void RepeatingAlarm::Cancel() {
  std::lock_guard<std::mutex> lock(mutex_);
  itimerspec disarm_itimerspec{/* disarm timer */};
  int result = timerfd_settime(fd_, 0, &disarm_itimerspec, nullptr);
  ASSERT(result == 0);
}

void RepeatingAlarm::on_fire() {
  std::unique_lock<std::mutex> lock(mutex_);
  auto task = task_;
  uint64_t times_invoked;
  auto bytes_read = read(fd_, &times_invoked, sizeof(uint64_t));
  lock.unlock();
  task.Run();
  ASSERT(bytes_read == static_cast<ssize_t>(sizeof(uint64_t)));
}

}  // namespace os
}  // namespace bluetooth