xref: /aosp_15_r20/external/pigweed/pw_bluetooth_proxy/h4_storage.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_bluetooth_proxy/internal/h4_storage.h"
16 
17 #include <mutex>
18 
19 #include "pw_assert/check.h"  // IWYU pragma: keep
20 
21 namespace pw::bluetooth::proxy {
22 
23 std::array<containers::Pair<uint8_t*, bool>, H4Storage::kNumH4Buffs>
InitOccupiedMap()24 H4Storage::InitOccupiedMap() {
25   std::lock_guard lock(storage_mutex_);
26   std::array<containers::Pair<uint8_t*, bool>, kNumH4Buffs> arr;
27   for (size_t i = 0; i < kNumH4Buffs; ++i) {
28     arr[i] = {h4_buffs_[i].data(), false};
29   }
30   return arr;
31 }
32 
H4Storage()33 H4Storage::H4Storage() : h4_buff_occupied_(InitOccupiedMap()) {}
34 
ReserveH4Buff()35 std::optional<pw::span<uint8_t>> H4Storage::ReserveH4Buff() {
36   std::lock_guard lock(storage_mutex_);
37   for (const auto& [buff, occupied] : h4_buff_occupied_) {
38     if (!occupied) {
39       h4_buff_occupied_.at(buff) = true;
40       return {{buff, kH4BuffSize}};
41     }
42   }
43   return std::nullopt;
44 }
45 
ReleaseH4Buff(const uint8_t * buffer)46 void H4Storage::ReleaseH4Buff(const uint8_t* buffer) {
47   std::lock_guard lock(storage_mutex_);
48   PW_CHECK(h4_buff_occupied_.contains(const_cast<uint8_t*>(buffer)),
49            "Received release callback for invalid buffer address.");
50 
51   h4_buff_occupied_.at(const_cast<uint8_t*>(buffer)) = false;
52 }
53 
Reset()54 void H4Storage::Reset() {
55   std::lock_guard lock(storage_mutex_);
56   for (const auto& [buff, _] : h4_buff_occupied_) {
57     h4_buff_occupied_.at(buff) = false;
58   }
59 }
60 
61 }  // namespace pw::bluetooth::proxy
62