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