• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "common/bind.h"
24 #include "os/log.h"
25 #include "os/utils.h"
26 
27 #ifdef OS_ANDROID
28 #define ALARM_CLOCK CLOCK_BOOTTIME_ALARM
29 #else
30 #define ALARM_CLOCK CLOCK_BOOTTIME
31 #endif
32 
33 namespace bluetooth {
34 namespace os {
35 
RepeatingAlarm(Handler * handler)36 RepeatingAlarm::RepeatingAlarm(Handler* handler) : handler_(handler), fd_(timerfd_create(ALARM_CLOCK, 0)) {
37   ASSERT(fd_ != -1);
38 
39   token_ = handler_->thread_->GetReactor()->Register(
40       fd_, common::Bind(&RepeatingAlarm::on_fire, common::Unretained(this)), common::Closure());
41 }
42 
~RepeatingAlarm()43 RepeatingAlarm::~RepeatingAlarm() {
44   handler_->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_, &times_invoked, sizeof(uint64_t));
76   lock.unlock();
77   task.Run();
78   ASSERT(bytes_read == static_cast<ssize_t>(sizeof(uint64_t)));
79 }
80 
81 }  // namespace os
82 }  // namespace bluetooth
83