• 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/handler.h"
18 
19 #include <sys/eventfd.h>
20 #include <cstring>
21 #include <unistd.h>
22 
23 #include "os/log.h"
24 #include "os/reactor.h"
25 #include "os/utils.h"
26 
27 #ifndef EFD_SEMAPHORE
28 #define EFD_SEMAPHORE 1
29 #endif
30 
31 namespace bluetooth {
32 namespace os {
33 
Handler(Thread * thread)34 Handler::Handler(Thread* thread)
35   : thread_(thread),
36     fd_(eventfd(0, EFD_SEMAPHORE | EFD_NONBLOCK)) {
37   ASSERT(fd_ != -1);
38 
39   reactable_ = thread_->GetReactor()->Register(fd_, [this] { this->handle_next_event(); }, nullptr);
40 }
41 
~Handler()42 Handler::~Handler() {
43   thread_->GetReactor()->Unregister(reactable_);
44   reactable_ = nullptr;
45 
46   int close_status;
47   RUN_NO_INTR(close_status = close(fd_));
48   ASSERT(close_status != -1);
49 }
50 
Post(Closure closure)51 void Handler::Post(Closure closure) {
52   {
53     std::lock_guard<std::mutex> lock(mutex_);
54     tasks_.emplace(std::move(closure));
55   }
56   uint64_t val = 1;
57   auto write_result = eventfd_write(fd_, val);
58   ASSERT(write_result != -1);
59 }
60 
Clear()61 void Handler::Clear() {
62   std::lock_guard<std::mutex> lock(mutex_);
63 
64   std::queue<Closure> empty;
65   std::swap(tasks_, empty);
66 
67   uint64_t val;
68   while (eventfd_read(fd_, &val) == 0) {
69   }
70 }
71 
handle_next_event()72 void Handler::handle_next_event() {
73   Closure closure;
74   uint64_t val = 0;
75   auto read_result = eventfd_read(fd_, &val);
76   if (read_result == -1 && errno == EAGAIN) {
77     // We were told there was an item, but it was removed before we got there
78     // (aka the queue was cleared). Not a fatal error, so just bail.
79     return;
80   }
81 
82   ASSERT(read_result != -1);
83 
84   {
85     std::lock_guard<std::mutex> lock(mutex_);
86     closure = std::move(tasks_.front());
87     tasks_.pop();
88   }
89   closure();
90 }
91 
92 }  // namespace os
93 }  // namespace bluetooth
94