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