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 "reactive_semaphore.h"
18 
19 #include <error.h>
20 #include <string.h>
21 #include <sys/eventfd.h>
22 #include <unistd.h>
23 
24 #include <functional>
25 
26 #include "os/linux_generic/linux.h"
27 #include "os/log.h"
28 
29 namespace bluetooth {
30 namespace os {
31 
ReactiveSemaphore(unsigned int value)32 ReactiveSemaphore::ReactiveSemaphore(unsigned int value) : fd_(eventfd(value, EFD_SEMAPHORE | EFD_NONBLOCK)) {
33   ASSERT(fd_ != -1);
34 }
35 
~ReactiveSemaphore()36 ReactiveSemaphore::~ReactiveSemaphore() {
37   int close_status;
38   RUN_NO_INTR(close_status = close(fd_));
39   ASSERT_LOG(close_status != -1, "close failed: %s", strerror(errno));
40 }
41 
Decrease()42 void ReactiveSemaphore::Decrease() {
43   uint64_t val = 0;
44   auto read_result = eventfd_read(fd_, &val);
45   ASSERT_LOG(read_result != -1, "decrease failed: %s", strerror(errno));
46 }
47 
Increase()48 void ReactiveSemaphore::Increase() {
49   uint64_t val = 1;
50   auto write_result = eventfd_write(fd_, val);
51   ASSERT_LOG(write_result != -1, "increase failed: %s", strerror(errno));
52 }
53 
GetFd()54 int ReactiveSemaphore::GetFd() {
55   return fd_;
56 }
57 
58 }  // namespace os
59 }  // namespace bluetooth
60