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/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 using common::OnceClosure;
39 
Alarm(Handler * handler)40 Alarm::Alarm(Handler* handler) : handler_(handler), fd_(TIMERFD_CREATE(ALARM_CLOCK, 0)) {
41   ASSERT_LOG(fd_ != -1, "cannot create timerfd: %s", strerror(errno));
42 
43   token_ = handler_->thread_->GetReactor()->Register(
44       fd_, common::Bind(&Alarm::on_fire, common::Unretained(this)), Closure());
45 }
46 
~Alarm()47 Alarm::~Alarm() {
48   handler_->thread_->GetReactor()->Unregister(token_);
49 
50   int close_status;
51   RUN_NO_INTR(close_status = TIMERFD_CLOSE(fd_));
52   ASSERT(close_status != -1);
53 }
54 
Schedule(OnceClosure task,std::chrono::milliseconds delay)55 void Alarm::Schedule(OnceClosure task, std::chrono::milliseconds delay) {
56   std::lock_guard<std::mutex> lock(mutex_);
57   long delay_ms = delay.count();
58   itimerspec timer_itimerspec{{/* interval for periodic timer */}, {delay_ms / 1000, delay_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 Alarm::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 Alarm::on_fire() {
73   std::unique_lock<std::mutex> lock(mutex_);
74   auto task = std::move(task_);
75   uint64_t times_invoked;
76   auto bytes_read = read(fd_, &times_invoked, sizeof(uint64_t));
77   lock.unlock();
78   std::move(task).Run();
79   ASSERT(bytes_read == static_cast<ssize_t>(sizeof(uint64_t)));
80   ASSERT(times_invoked == static_cast<uint64_t>(1));
81 }
82 
83 }  // namespace os
84 }  // namespace bluetooth
85