1 /*
2 * Copyright 2019 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 "os/repeating_alarm.h"
18
19 #include <sys/timerfd.h>
20 #include <cstring>
21 #include <unistd.h>
22
23 #include "os/log.h"
24 #include "os/utils.h"
25
26 #ifdef OS_ANDROID
27 #define ALARM_CLOCK CLOCK_BOOTTIME_ALARM
28 #else
29 #define ALARM_CLOCK CLOCK_BOOTTIME
30 #endif
31
32 namespace bluetooth {
33 namespace os {
34
RepeatingAlarm(Thread * thread)35 RepeatingAlarm::RepeatingAlarm(Thread* thread)
36 : thread_(thread),
37 fd_(timerfd_create(ALARM_CLOCK, 0)) {
38 ASSERT(fd_ != -1);
39
40 token_ = thread_->GetReactor()->Register(fd_, [this] { on_fire(); }, nullptr);
41 }
42
~RepeatingAlarm()43 RepeatingAlarm::~RepeatingAlarm() {
44 thread_->GetReactor()->Unregister(token_);
45
46 int close_status;
47 RUN_NO_INTR(close_status = close(fd_));
48 ASSERT(close_status != -1);
49 }
50
Schedule(Closure task,std::chrono::milliseconds period)51 void RepeatingAlarm::Schedule(Closure task, std::chrono::milliseconds period) {
52 std::lock_guard<std::mutex> lock(mutex_);
53 long period_ms = period.count();
54 itimerspec timer_itimerspec{
55 {period_ms / 1000, period_ms % 1000 * 1000000},
56 {period_ms / 1000, period_ms % 1000 * 1000000}
57 };
58 int result = timerfd_settime(fd_, 0, &timer_itimerspec, nullptr);
59 ASSERT(result == 0);
60
61 task_ = std::move(task);
62 }
63
Cancel()64 void RepeatingAlarm::Cancel() {
65 std::lock_guard<std::mutex> lock(mutex_);
66 itimerspec disarm_itimerspec{/* disarm timer */};
67 int result = timerfd_settime(fd_, 0, &disarm_itimerspec, nullptr);
68 ASSERT(result == 0);
69 }
70
on_fire()71 void RepeatingAlarm::on_fire() {
72 std::unique_lock<std::mutex> lock(mutex_);
73 auto task = task_;
74 uint64_t times_invoked;
75 auto bytes_read = read(fd_, ×_invoked, sizeof(uint64_t));
76 lock.unlock();
77 task();
78 ASSERT(bytes_read == static_cast<ssize_t>(sizeof(uint64_t)));
79 }
80
81 } // namespace os
82 } // namespace bluetooth
83