• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 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 "main/shim/acl.h"
18 
19 #include <base/location.h>
20 #include <bluetooth/log.h>
21 #include <com_android_bluetooth_flags.h>
22 #include <time.h>
23 
24 #include <chrono>
25 #include <cstdint>
26 #include <deque>
27 #include <functional>
28 #include <future>
29 #include <map>
30 #include <memory>
31 #include <optional>
32 #include <queue>
33 #include <string>
34 #include <unordered_set>
35 #include <utility>
36 #include <vector>
37 
38 #include "common/bind.h"
39 #include "common/strings.h"
40 #include "common/sync_map_count.h"
41 #include "hci/acl_manager.h"
42 #include "hci/acl_manager/acl_connection.h"
43 #include "hci/acl_manager/classic_acl_connection.h"
44 #include "hci/acl_manager/connection_management_callbacks.h"
45 #include "hci/acl_manager/le_acl_connection.h"
46 #include "hci/acl_manager/le_connection_management_callbacks.h"
47 #include "hci/address.h"
48 #include "hci/address_with_type.h"
49 #include "hci/class_of_device.h"
50 #include "hci/controller_interface.h"
51 #include "internal_include/bt_target.h"
52 #include "main/shim/dumpsys.h"
53 #include "main/shim/entry.h"
54 #include "main/shim/helpers.h"
55 #include "main/shim/stack.h"
56 #include "metrics/bluetooth_event.h"
57 #include "os/handler.h"
58 #include "os/wakelock_manager.h"
59 #include "osi/include/alarm.h"
60 #include "osi/include/allocator.h"
61 #include "osi/include/properties.h"
62 #include "stack/acl/acl.h"
63 #include "stack/btm/btm_int_types.h"
64 #include "stack/include/bt_hdr.h"
65 #include "stack/include/btm_log_history.h"
66 #include "stack/include/main_thread.h"
67 #include "types/ble_address_with_type.h"
68 #include "types/raw_address.h"
69 
70 extern tBTM_CB btm_cb;
71 
72 using namespace bluetooth;
73 using ::bluetooth::os::WakelockManager;
74 
75 class ConnectAddressWithType {
76 public:
ConnectAddressWithType(hci::AddressWithType address_with_type)77   explicit ConnectAddressWithType(hci::AddressWithType address_with_type)
78       : address_(address_with_type.GetAddress()),
79         type_(address_with_type.ToFilterAcceptListAddressType()) {}
80 
81   // TODO: remove this method
ToString() const82   std::string const ToString() const {
83     std::stringstream ss;
84     ss << address_.ToString() << "[" << FilterAcceptListAddressTypeText(type_) << "]";
85     return ss.str();
86   }
87 
ToStringForLogging() const88   std::string ToStringForLogging() const { return ToString(); }
ToRedactedStringForLogging() const89   std::string ToRedactedStringForLogging() const {
90     std::stringstream ss;
91     ss << address_.ToRedactedStringForLogging() << "[" << FilterAcceptListAddressTypeText(type_)
92        << "]";
93     return ss.str();
94   }
operator ==(const ConnectAddressWithType & rhs) const95   bool operator==(const ConnectAddressWithType& rhs) const {
96     return address_ == rhs.address_ && type_ == rhs.type_;
97   }
98 
99 private:
100   friend std::hash<ConnectAddressWithType>;
101   hci::Address address_;
102   hci::FilterAcceptListAddressType type_;
103 };
104 
105 namespace std {
106 template <>
107 struct hash<ConnectAddressWithType> {
operator ()std::hash108   std::size_t operator()(const ConnectAddressWithType& val) const {
109     static_assert(sizeof(uint64_t) >= (bluetooth::hci::Address::kLength +
110                                        sizeof(bluetooth::hci::FilterAcceptListAddressType)));
111     uint64_t int_addr = 0;
112     memcpy(reinterpret_cast<uint8_t*>(&int_addr), val.address_.data(),
113            bluetooth::hci::Address::kLength);
114     memcpy(reinterpret_cast<uint8_t*>(&int_addr) + bluetooth::hci::Address::kLength, &val.type_,
115            sizeof(bluetooth::hci::FilterAcceptListAddressType));
116     return std::hash<uint64_t>{}(int_addr);
117   }
118 };
119 }  // namespace std
120 
121 namespace std {
122 template <>
123 struct formatter<ConnectAddressWithType> : formatter<std::string> {
124   template <class Context>
formatstd::formatter125   typename Context::iterator format(const ConnectAddressWithType& address, Context& ctx) const {
126     std::string repr = address.ToRedactedStringForLogging();
127     return std::formatter<std::string>::format(repr, ctx);
128   }
129 };
130 }  // namespace std
131 
132 namespace {
133 
wakelock_release_cb(void *)134 static void wakelock_release_cb(void*) {
135   log::debug("Wakelock released on timeout");
136   WakelockManager::Get().Release();
137 }
138 
139 struct timed_wakelock {
timed_wakelock__anona3c738fc0111::timed_wakelock140   timed_wakelock() { timer_ = alarm_new("bluetooth_wakelock_timer"); }
~timed_wakelock__anona3c738fc0111::timed_wakelock141   ~timed_wakelock() {
142     if (alarm_is_scheduled(timer_)) {
143       log::debug("Wakelock released");
144       WakelockManager::Get().Release();
145     }
146     alarm_free(timer_);
147   }
148 
149   // Acquire wakelock for a fixed time.
150   // Acquiring again resets the timer. Wakelock is released after the time.
acquire__anona3c738fc0111::timed_wakelock151   void acquire(uint64_t timeout_ms) {
152     // Ignore request if timeout is 0.
153     if (timeout_ms == 0) {
154       return;
155     }
156     if (!alarm_is_scheduled(timer_)) {
157       log::debug("Wakelock acquired");
158       WakelockManager::Get().Acquire();
159     } else {
160       alarm_cancel(timer_);
161     }
162     log::debug("Alarm set for {} ms", timeout_ms);
163     alarm_set_on_mloop(timer_, timeout_ms, wakelock_release_cb, nullptr);
164   }
165 
166   // Cancel timer and release wakelock.
release__anona3c738fc0111::timed_wakelock167   void release() {
168     if (alarm_is_scheduled(timer_)) {
169       log::debug("Wakelock released early. Time left: {} ms", alarm_get_remaining_ms(timer_));
170       alarm_cancel(timer_);
171       WakelockManager::Get().Release();
172     }
173   }
174 
175 private:
176   alarm_t* timer_ = nullptr;  // wakelock state is given by alarm_is_scheduled
177 };  // timed_wakelock
178 
179 constexpr uint32_t kRunicBjarkan = 0x0016D2;
180 constexpr uint32_t kRunicHagall = 0x0016BC;
181 
182 using HciHandle = uint16_t;
183 using PageNumber = uint8_t;
184 
185 using CreationTime = std::chrono::time_point<std::chrono::system_clock>;
186 using TeardownTime = std::chrono::time_point<std::chrono::system_clock>;
187 
188 constexpr char kBtmLogTag[] = "ACL";
189 constexpr char kWakelockTimeoutMsSysprop[] = "bluetooth.core.acl.wakelock_timeout";
190 
191 using SendDataUpwards = void (*const)(BT_HDR*);
192 using OnDisconnect = std::function<void(HciHandle, hci::ErrorCode reason)>;
193 
194 constexpr char kConnectionDescriptorTimeFormat[] = "%Y-%m-%d %H:%M:%S";
195 
196 constexpr unsigned MillisPerSecond = 1000;
EpochMillisToString(long long time_ms)197 std::string EpochMillisToString(long long time_ms) {
198   time_t time_sec = time_ms / MillisPerSecond;
199   struct tm tm;
200   localtime_r(&time_sec, &tm);
201   std::string s = common::StringFormatTime(kConnectionDescriptorTimeFormat, tm);
202   return std::format("{}.{:03}", s, time_ms % MillisPerSecond);
203 }
204 
205 class ShadowAddressResolutionList {
206 public:
ShadowAddressResolutionList(uint8_t max_address_resolution_size)207   explicit ShadowAddressResolutionList(uint8_t max_address_resolution_size)
208       : max_address_resolution_size_(max_address_resolution_size) {}
209 
Add(const hci::AddressWithType & address_with_type)210   bool Add(const hci::AddressWithType& address_with_type) {
211     if (address_resolution_set_.size() == max_address_resolution_size_) {
212       log::error("Address Resolution is full size:{}", address_resolution_set_.size());
213       return false;
214     }
215     if (!address_resolution_set_.insert(address_with_type).second) {
216       log::warn("Attempted to add duplicate le address to address_resolution:{}",
217                 address_with_type);
218     }
219     return true;
220   }
221 
Remove(const hci::AddressWithType & address_with_type)222   bool Remove(const hci::AddressWithType& address_with_type) {
223     auto iter = address_resolution_set_.find(address_with_type);
224     if (iter == address_resolution_set_.end()) {
225       log::warn("Unknown device being removed from address_resolution:{}", address_with_type);
226       return false;
227     }
228     address_resolution_set_.erase(iter);
229     return true;
230   }
231 
GetCopy() const232   std::unordered_set<hci::AddressWithType> GetCopy() const { return address_resolution_set_; }
233 
IsFull() const234   bool IsFull() const {
235     return address_resolution_set_.size() == static_cast<size_t>(max_address_resolution_size_);
236   }
237 
Size() const238   size_t Size() const { return address_resolution_set_.size(); }
239 
Clear()240   void Clear() { address_resolution_set_.clear(); }
241 
GetMaxSize() const242   uint8_t GetMaxSize() const { return max_address_resolution_size_; }
243 
244 private:
245   uint8_t max_address_resolution_size_{0};
246   std::unordered_set<hci::AddressWithType> address_resolution_set_;
247 };
248 
249 struct ConnectionDescriptor {
250   CreationTime creation_time_;
251   TeardownTime teardown_time_;
252   uint16_t handle_;
253   bool is_locally_initiated_;
254   hci::ErrorCode disconnect_reason_;
ConnectionDescriptor__anona3c738fc0111::ConnectionDescriptor255   ConnectionDescriptor(CreationTime creation_time, TeardownTime teardown_time, uint16_t handle,
256                        bool is_locally_initiated, hci::ErrorCode disconnect_reason)
257       : creation_time_(creation_time),
258         teardown_time_(teardown_time),
259         handle_(handle),
260         is_locally_initiated_(is_locally_initiated),
261         disconnect_reason_(disconnect_reason) {}
262   virtual std::string GetPrivateRemoteAddress() const = 0;
~ConnectionDescriptor__anona3c738fc0111::ConnectionDescriptor263   virtual ~ConnectionDescriptor() {}
ToString__anona3c738fc0111::ConnectionDescriptor264   std::string ToString() const {
265     return std::format(
266             "peer:{} handle:0x{:04x} is_locally_initiated:{} creation_time:{} teardown_time:{} "
267             "disconnect_reason:{}",
268             GetPrivateRemoteAddress(), handle_, is_locally_initiated_,
269             common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat,
270                                                      creation_time_),
271             common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat,
272                                                      teardown_time_),
273             hci::ErrorCodeText(disconnect_reason_));
274   }
275 };
276 
277 struct ClassicConnectionDescriptor : public ConnectionDescriptor {
278   const hci::Address remote_address_;
ClassicConnectionDescriptor__anona3c738fc0111::ClassicConnectionDescriptor279   ClassicConnectionDescriptor(const hci::Address& remote_address, CreationTime creation_time,
280                               TeardownTime teardown_time, uint16_t handle,
281                               bool is_locally_initiated, hci::ErrorCode disconnect_reason)
282       : ConnectionDescriptor(creation_time, teardown_time, handle, is_locally_initiated,
283                              disconnect_reason),
284         remote_address_(remote_address) {}
GetPrivateRemoteAddress__anona3c738fc0111::ClassicConnectionDescriptor285   virtual std::string GetPrivateRemoteAddress() const {
286     return remote_address_.ToRedactedStringForLogging();
287   }
288 };
289 
290 struct LeConnectionDescriptor : public ConnectionDescriptor {
291   const hci::AddressWithType remote_address_with_type_;
LeConnectionDescriptor__anona3c738fc0111::LeConnectionDescriptor292   LeConnectionDescriptor(hci::AddressWithType& remote_address_with_type, CreationTime creation_time,
293                          TeardownTime teardown_time, uint16_t handle, bool is_locally_initiated,
294                          hci::ErrorCode disconnect_reason)
295       : ConnectionDescriptor(creation_time, teardown_time, handle, is_locally_initiated,
296                              disconnect_reason),
297         remote_address_with_type_(remote_address_with_type) {}
GetPrivateRemoteAddress__anona3c738fc0111::LeConnectionDescriptor298   std::string GetPrivateRemoteAddress() const {
299     return remote_address_with_type_.ToRedactedStringForLogging();
300   }
301 };
302 
303 template <typename T>
304 class FixedQueue {
305 public:
FixedQueue(size_t max_size)306   explicit FixedQueue(size_t max_size) : max_size_(max_size) {}
Push(T element)307   void Push(T element) {
308     if (queue_.size() == max_size_) {
309       queue_.pop_front();
310     }
311     queue_.push_back(std::move(element));
312   }
313 
ReadElementsAsString() const314   std::vector<std::string> ReadElementsAsString() const {
315     std::vector<std::string> vector;
316     for (auto& entry : queue_) {
317       vector.push_back(entry->ToString());
318     }
319     return vector;
320   }
321 
322 private:
323   size_t max_size_{1};
324   std::deque<T> queue_;
325 };
326 
327 constexpr size_t kConnectionHistorySize = 40;
328 
LowByte(uint16_t val)329 inline uint8_t LowByte(uint16_t val) { return val & 0xff; }
HighByte(uint16_t val)330 inline uint8_t HighByte(uint16_t val) { return val >> 8; }
331 
ValidateAclInterface(const shim::acl_interface_t & acl_interface)332 void ValidateAclInterface(const shim::acl_interface_t& acl_interface) {
333   log::assert_that(acl_interface.on_send_data_upwards != nullptr,
334                    "Must provide to receive data on acl links");
335   log::assert_that(acl_interface.on_packets_completed != nullptr,
336                    "Must provide to receive completed packet indication");
337 
338   log::assert_that(acl_interface.connection.classic.on_connected != nullptr,
339                    "Must provide to respond to successful classic connections");
340   log::assert_that(acl_interface.connection.classic.on_failed != nullptr,
341                    "Must provide to respond when classic connection attempts fail");
342   log::assert_that(acl_interface.connection.classic.on_disconnected != nullptr,
343                    "Must provide to respond when active classic connection disconnects");
344 
345   log::assert_that(acl_interface.connection.le.on_connected != nullptr,
346                    "Must provide to respond to successful le connections");
347   log::assert_that(acl_interface.connection.le.on_failed != nullptr,
348                    "Must provide to respond when le connection attempts fail");
349   log::assert_that(acl_interface.connection.le.on_disconnected != nullptr,
350                    "Must provide to respond when active le connection disconnects");
351 }
352 
353 }  // namespace
354 
355 #define TRY_POSTING_ON_MAIN(cb, ...)                        \
356   do {                                                      \
357     if (cb == nullptr) {                                    \
358       log::warn("Dropping ACL event with no callback");     \
359     } else {                                                \
360       do_in_main_thread(base::BindOnce(cb, ##__VA_ARGS__)); \
361     }                                                       \
362   } while (0)
363 
364 constexpr HciHandle kInvalidHciHandle = 0xffff;
365 
366 class ShimAclConnection {
367 public:
ShimAclConnection(const HciHandle handle,SendDataUpwards send_data_upwards,os::Handler * handler,hci::acl_manager::AclConnection::QueueUpEnd * queue_up_end,CreationTime creation_time)368   ShimAclConnection(const HciHandle handle, SendDataUpwards send_data_upwards, os::Handler* handler,
369                     hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end,
370                     CreationTime creation_time)
371       : handle_(handle),
372         handler_(handler),
373         send_data_upwards_(send_data_upwards),
374         queue_up_end_(queue_up_end),
375         creation_time_(creation_time) {
376     queue_up_end_->RegisterDequeue(handler_, common::Bind(&ShimAclConnection::data_ready_callback,
377                                                           common::Unretained(this)));
378   }
379 
~ShimAclConnection()380   virtual ~ShimAclConnection() {
381     if (!queue_.empty()) {
382       log::error(
383               "ACL cleaned up with non-empty queue handle:0x{:04x} "
384               "stranded_pkts:{}",
385               handle_, queue_.size());
386     }
387     log::assert_that(is_disconnected_, "Shim Acl was not properly disconnected handle:0x{:04x}",
388                      handle_);
389   }
390 
EnqueuePacket(std::unique_ptr<packet::RawBuilder> packet)391   void EnqueuePacket(std::unique_ptr<packet::RawBuilder> packet) {
392     // TODO Handle queue size exceeds some threshold
393     queue_.push(std::move(packet));
394     RegisterEnqueue();
395   }
396 
handle_enqueue()397   std::unique_ptr<packet::BasePacketBuilder> handle_enqueue() {
398     auto packet = std::move(queue_.front());
399     queue_.pop();
400     if (queue_.empty()) {
401       UnregisterEnqueue();
402     }
403     return packet;
404   }
405 
data_ready_callback()406   void data_ready_callback() {
407     auto packet = queue_up_end_->TryDequeue();
408     uint16_t length = packet->size();
409     std::vector<uint8_t> preamble;
410     preamble.push_back(LowByte(handle_));
411     preamble.push_back(HighByte(handle_));
412     preamble.push_back(LowByte(length));
413     preamble.push_back(HighByte(length));
414     BT_HDR* p_buf = MakeLegacyBtHdrPacket(std::move(packet), preamble);
415     log::assert_that(p_buf != nullptr, "Unable to allocate BT_HDR legacy packet handle:{:04x}",
416                      handle_);
417     if (send_data_upwards_ == nullptr) {
418       log::warn("Dropping ACL data with no callback");
419       osi_free(p_buf);
420     } else if (do_in_main_thread(base::BindOnce(send_data_upwards_, p_buf)) != BT_STATUS_SUCCESS) {
421       osi_free(p_buf);
422     }
423   }
424 
425   virtual void InitiateDisconnect(hci::DisconnectReason reason) = 0;
426   virtual bool IsLocallyInitiated() const = 0;
427 
GetCreationTime() const428   CreationTime GetCreationTime() const { return creation_time_; }
Handle() const429   uint16_t Handle() const { return handle_; }
430 
Shutdown()431   void Shutdown() {
432     Disconnect();
433     log::info("Shutdown and disconnect ACL connection handle:0x{:04x}", handle_);
434   }
435 
436 protected:
437   const uint16_t handle_{kInvalidHciHandle};
438   os::Handler* handler_;
439 
UnregisterEnqueue()440   void UnregisterEnqueue() {
441     if (!is_enqueue_registered_) {
442       return;
443     }
444     is_enqueue_registered_ = false;
445     queue_up_end_->UnregisterEnqueue();
446   }
447 
Disconnect()448   void Disconnect() {
449     if (is_disconnected_) {
450       log::error("Cannot disconnect ACL multiple times handle:{:04x} creation_time:{}", handle_,
451                  common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat,
452                                                           creation_time_));
453       return;
454     }
455     is_disconnected_ = true;
456     UnregisterEnqueue();
457     queue_up_end_->UnregisterDequeue();
458     if (!queue_.empty()) {
459       log::warn("ACL disconnect with non-empty queue handle:{:04x} stranded_pkts::{}", handle_,
460                 queue_.size());
461     }
462   }
463 
464   virtual void ReadRemoteControllerInformation() = 0;
465 
466 private:
467   SendDataUpwards send_data_upwards_;
468   hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end_;
469 
470   std::queue<std::unique_ptr<packet::RawBuilder>> queue_;
471   bool is_enqueue_registered_{false};
472   bool is_disconnected_{false};
473   CreationTime creation_time_;
474 
RegisterEnqueue()475   void RegisterEnqueue() {
476     log::assert_that(!is_disconnected_,
477                      "Unable to send data over disconnected channel handle:{:04x}", handle_);
478     if (is_enqueue_registered_) {
479       return;
480     }
481     is_enqueue_registered_ = true;
482     queue_up_end_->RegisterEnqueue(
483             handler_, common::Bind(&ShimAclConnection::handle_enqueue, common::Unretained(this)));
484   }
485 
486   virtual void RegisterCallbacks() = 0;
487 };
488 
489 class ClassicShimAclConnection : public ShimAclConnection,
490                                  public hci::acl_manager::ConnectionManagementCallbacks {
491 public:
ClassicShimAclConnection(SendDataUpwards send_data_upwards,OnDisconnect on_disconnect,const shim::acl_classic_link_interface_t & interface,os::Handler * handler,std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection,CreationTime creation_time)492   ClassicShimAclConnection(SendDataUpwards send_data_upwards, OnDisconnect on_disconnect,
493                            const shim::acl_classic_link_interface_t& interface,
494                            os::Handler* handler,
495                            std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection,
496                            CreationTime creation_time)
497       : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler,
498                           connection->GetAclQueueEnd(), creation_time),
499         on_disconnect_(on_disconnect),
500         interface_(interface),
501         connection_(std::move(connection)) {}
502 
RegisterCallbacks()503   void RegisterCallbacks() override { connection_->RegisterCallbacks(this, handler_); }
504 
ReadRemoteControllerInformation()505   void ReadRemoteControllerInformation() override {
506     connection_->ReadRemoteVersionInformation();
507     connection_->ReadRemoteSupportedFeatures();
508   }
509 
OnConnectionPacketTypeChanged(uint16_t packet_type)510   void OnConnectionPacketTypeChanged(uint16_t packet_type) override {
511     TRY_POSTING_ON_MAIN(interface_.on_packet_type_changed, packet_type);
512   }
513 
OnAuthenticationComplete(hci::ErrorCode hci_status)514   void OnAuthenticationComplete(hci::ErrorCode hci_status) override {
515     TRY_POSTING_ON_MAIN(interface_.on_authentication_complete, handle_,
516                         ToLegacyHciErrorCode(hci_status));
517   }
518 
OnEncryptionChange(hci::EncryptionEnabled enabled)519   void OnEncryptionChange(hci::EncryptionEnabled enabled) override {
520     bool is_enabled = (enabled == hci::EncryptionEnabled::ON ||
521                        enabled == hci::EncryptionEnabled::BR_EDR_AES_CCM);
522     TRY_POSTING_ON_MAIN(interface_.on_encryption_change, is_enabled);
523   }
524 
OnChangeConnectionLinkKeyComplete()525   void OnChangeConnectionLinkKeyComplete() override {
526     TRY_POSTING_ON_MAIN(interface_.on_change_connection_link_key_complete);
527   }
528 
OnReadClockOffsetComplete(uint16_t)529   void OnReadClockOffsetComplete(uint16_t /* clock_offset */) override {
530     log::info("UNIMPLEMENTED");
531   }
532 
OnModeChange(hci::ErrorCode status,hci::Mode current_mode,uint16_t interval)533   void OnModeChange(hci::ErrorCode status, hci::Mode current_mode, uint16_t interval) override {
534     TRY_POSTING_ON_MAIN(interface_.on_mode_change, ToLegacyHciErrorCode(status), handle_,
535                         ToLegacyHciMode(current_mode), interval);
536   }
537 
OnSniffSubrating(hci::ErrorCode hci_status,uint16_t maximum_transmit_latency,uint16_t maximum_receive_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)538   void OnSniffSubrating(hci::ErrorCode hci_status, uint16_t maximum_transmit_latency,
539                         uint16_t maximum_receive_latency, uint16_t minimum_remote_timeout,
540                         uint16_t minimum_local_timeout) {
541     TRY_POSTING_ON_MAIN(interface_.on_sniff_subrating, ToLegacyHciErrorCode(hci_status), handle_,
542                         maximum_transmit_latency, maximum_receive_latency, minimum_remote_timeout,
543                         minimum_local_timeout);
544   }
545 
OnQosSetupComplete(hci::ServiceType,uint32_t,uint32_t,uint32_t,uint32_t)546   void OnQosSetupComplete(hci::ServiceType /* service_type */, uint32_t /* token_rate */,
547                           uint32_t /* peak_bandwidth */, uint32_t /* latency */,
548                           uint32_t /* delay_variation */) override {
549     log::info("UNIMPLEMENTED");
550   }
551 
OnFlowSpecificationComplete(hci::FlowDirection,hci::ServiceType,uint32_t,uint32_t,uint32_t,uint32_t)552   void OnFlowSpecificationComplete(hci::FlowDirection /* flow_direction */,
553                                    hci::ServiceType /* service_type */, uint32_t /* token_rate */,
554                                    uint32_t /* token_bucket_size */, uint32_t /* peak_bandwidth */,
555                                    uint32_t /* access_latency */) override {
556     log::info("UNIMPLEMENTED");
557   }
558 
OnFlushOccurred()559   void OnFlushOccurred() override { log::info("UNIMPLEMENTED"); }
560 
OnRoleDiscoveryComplete(hci::Role)561   void OnRoleDiscoveryComplete(hci::Role /* current_role */) override {
562     log::info("UNIMPLEMENTED");
563   }
564 
OnReadLinkPolicySettingsComplete(uint16_t)565   void OnReadLinkPolicySettingsComplete(uint16_t /* link_policy_settings */) override {
566     log::info("UNIMPLEMENTED");
567   }
568 
OnReadAutomaticFlushTimeoutComplete(uint16_t)569   void OnReadAutomaticFlushTimeoutComplete(uint16_t /* flush_timeout */) override {
570     log::info("UNIMPLEMENTED");
571   }
572 
OnReadTransmitPowerLevelComplete(uint8_t)573   void OnReadTransmitPowerLevelComplete(uint8_t /* transmit_power_level */) override {
574     log::info("UNIMPLEMENTED");
575   }
576 
OnReadLinkSupervisionTimeoutComplete(uint16_t)577   void OnReadLinkSupervisionTimeoutComplete(uint16_t /* link_supervision_timeout */) override {
578     log::info("UNIMPLEMENTED");
579   }
580 
OnReadFailedContactCounterComplete(uint16_t)581   void OnReadFailedContactCounterComplete(uint16_t /* failed_contact_counter */) override {
582     log::info("UNIMPLEMENTED");
583   }
584 
OnReadLinkQualityComplete(uint8_t)585   void OnReadLinkQualityComplete(uint8_t /* link_quality */) override {
586     log::info("UNIMPLEMENTED");
587   }
588 
OnReadAfhChannelMapComplete(hci::AfhMode,std::array<uint8_t,10>)589   void OnReadAfhChannelMapComplete(hci::AfhMode /* afh_mode */,
590                                    std::array<uint8_t, 10> /* afh_channel_map */) override {
591     log::info("UNIMPLEMENTED");
592   }
593 
OnReadRssiComplete(uint8_t)594   void OnReadRssiComplete(uint8_t /* rssi */) override { log::info("UNIMPLEMENTED"); }
595 
OnReadClockComplete(uint32_t,uint16_t)596   void OnReadClockComplete(uint32_t /* clock */, uint16_t /* accuracy */) override {
597     log::info("UNIMPLEMENTED");
598   }
599 
OnCentralLinkKeyComplete(hci::KeyFlag)600   void OnCentralLinkKeyComplete(hci::KeyFlag /* key_flag */) override {
601     log::info("UNIMPLEMENTED");
602   }
603 
OnRoleChange(hci::ErrorCode hci_status,hci::Role new_role)604   void OnRoleChange(hci::ErrorCode hci_status, hci::Role new_role) override {
605     TRY_POSTING_ON_MAIN(interface_.on_role_change, ToLegacyHciErrorCode(hci_status),
606                         ToRawAddress(connection_->GetAddress()), ToLegacyRole(new_role));
607     BTM_LogHistory(kBtmLogTag, ToRawAddress(connection_->GetAddress()), "Role change",
608                    std::format("classic New_role:{} status:{}", hci::RoleText(new_role),
609                                hci::ErrorCodeText(hci_status)));
610   }
611 
OnDisconnection(hci::ErrorCode reason)612   void OnDisconnection(hci::ErrorCode reason) override {
613     Disconnect();
614     on_disconnect_(handle_, reason);
615   }
616 
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)617   void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version,
618                                               uint16_t manufacturer_name,
619                                               uint16_t sub_version) override {
620     TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete,
621                         ToLegacyHciErrorCode(hci_status), handle_, lmp_version, manufacturer_name,
622                         sub_version);
623   }
624 
OnReadRemoteSupportedFeaturesComplete(uint64_t features)625   void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override {
626     TRY_POSTING_ON_MAIN(interface_.on_read_remote_supported_features_complete, handle_, features);
627 
628     if (features & (uint64_t(1) << 63)) {
629       connection_->ReadRemoteExtendedFeatures(1);
630       return;
631     }
632     log::debug("Device does not support extended features");
633   }
634 
OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,uint8_t max_page_number,uint64_t features)635   void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number, uint8_t max_page_number,
636                                             uint64_t features) override {
637     TRY_POSTING_ON_MAIN(interface_.on_read_remote_extended_features_complete, handle_, page_number,
638                         max_page_number, features);
639 
640     // Supported features aliases to extended features page 0
641     if (page_number == 0 && !(features & (uint64_t(1) << 63))) {
642       log::debug("Device does not support extended features");
643       return;
644     }
645 
646     if (max_page_number != 0 && page_number != max_page_number) {
647       connection_->ReadRemoteExtendedFeatures(page_number + 1);
648     }
649   }
650 
GetRemoteAddress() const651   hci::Address GetRemoteAddress() const { return connection_->GetAddress(); }
652 
InitiateDisconnect(hci::DisconnectReason reason)653   void InitiateDisconnect(hci::DisconnectReason reason) override {
654     connection_->Disconnect(reason);
655   }
656 
HoldMode(uint16_t max_interval,uint16_t min_interval)657   void HoldMode(uint16_t max_interval, uint16_t min_interval) {
658     log::assert_that(connection_->HoldMode(max_interval, min_interval),
659                      "assert failed: connection_->HoldMode(max_interval, min_interval)");
660   }
661 
SniffMode(uint16_t max_interval,uint16_t min_interval,uint16_t attempt,uint16_t timeout)662   void SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt, uint16_t timeout) {
663     log::assert_that(connection_->SniffMode(max_interval, min_interval, attempt, timeout),
664                      "assert failed:  connection_->SniffMode(max_interval, min_interval, "
665                      "attempt, timeout)");
666   }
667 
ExitSniffMode()668   void ExitSniffMode() {
669     log::assert_that(connection_->ExitSniffMode(), "assert failed: connection_->ExitSniffMode()");
670   }
671 
SniffSubrating(uint16_t maximum_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)672   void SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout,
673                       uint16_t minimum_local_timeout) {
674     log::assert_that(connection_->SniffSubrating(maximum_latency, minimum_remote_timeout,
675                                                  minimum_local_timeout),
676                      "assert failed: connection_->SniffSubrating(maximum_latency, "
677                      "minimum_remote_timeout, minimum_local_timeout)");
678   }
679 
SetConnectionEncryption(hci::Enable is_encryption_enabled)680   void SetConnectionEncryption(hci::Enable is_encryption_enabled) {
681     log::assert_that(connection_->SetConnectionEncryption(is_encryption_enabled),
682                      "assert failed: "
683                      "connection_->SetConnectionEncryption(is_encryption_enabled)");
684   }
685 
IsLocallyInitiated() const686   bool IsLocallyInitiated() const override { return connection_->locally_initiated_; }
687 
Flush()688   void Flush() { connection_->Flush(); }
689 
690 private:
691   OnDisconnect on_disconnect_;
692   const shim::acl_classic_link_interface_t interface_;
693   std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection_;
694 };
695 
696 class LeShimAclConnection : public ShimAclConnection,
697                             public hci::acl_manager::LeConnectionManagementCallbacks {
698 public:
LeShimAclConnection(SendDataUpwards send_data_upwards,OnDisconnect on_disconnect,const shim::acl_le_link_interface_t & interface,os::Handler * handler,std::unique_ptr<hci::acl_manager::LeAclConnection> connection,std::chrono::time_point<std::chrono::system_clock> creation_time)699   LeShimAclConnection(SendDataUpwards send_data_upwards, OnDisconnect on_disconnect,
700                       const shim::acl_le_link_interface_t& interface, os::Handler* handler,
701                       std::unique_ptr<hci::acl_manager::LeAclConnection> connection,
702                       std::chrono::time_point<std::chrono::system_clock> creation_time)
703       : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler,
704                           connection->GetAclQueueEnd(), creation_time),
705         on_disconnect_(on_disconnect),
706         interface_(interface),
707         connection_(std::move(connection)) {}
708 
RegisterCallbacks()709   void RegisterCallbacks() override { connection_->RegisterCallbacks(this, handler_); }
710 
LeSubrateRequest(uint16_t subrate_min,uint16_t subrate_max,uint16_t max_latency,uint16_t cont_num,uint16_t sup_tout)711   void LeSubrateRequest(uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency,
712                         uint16_t cont_num, uint16_t sup_tout) {
713     connection_->LeSubrateRequest(subrate_min, subrate_max, max_latency, cont_num, sup_tout);
714   }
715 
ReadRemoteControllerInformation()716   void ReadRemoteControllerInformation() override {
717     // TODO Issue LeReadRemoteFeatures Command
718   }
719 
GetLocalAddressWithType()720   bluetooth::hci::AddressWithType GetLocalAddressWithType() {
721     return connection_->GetLocalAddress();
722   }
723 
GetLocalOtaAddressWithType()724   bluetooth::hci::AddressWithType GetLocalOtaAddressWithType() {
725     return connection_->GetLocalOtaAddress();
726   }
727 
GetPeerAddressWithType()728   bluetooth::hci::AddressWithType GetPeerAddressWithType() { return connection_->GetPeerAddress(); }
729 
GetPeerOtaAddressWithType()730   bluetooth::hci::AddressWithType GetPeerOtaAddressWithType() {
731     return connection_->GetPeerOtaAddress();
732   }
733 
GetAdvertisingSetConnectedTo()734   std::optional<uint8_t> GetAdvertisingSetConnectedTo() {
735     return std::visit(
736             [](auto&& data) {
737               using T = std::decay_t<decltype(data)>;
738               if constexpr (std::is_same_v<T, hci::acl_manager::DataAsPeripheral>) {
739                 return data.advertising_set_id;
740               } else {
741                 return std::optional<uint8_t>{};
742               }
743             },
744             connection_->GetRoleSpecificData());
745   }
746 
OnConnectionUpdate(hci::ErrorCode hci_status,uint16_t connection_interval,uint16_t connection_latency,uint16_t supervision_timeout)747   void OnConnectionUpdate(hci::ErrorCode hci_status, uint16_t connection_interval,
748                           uint16_t connection_latency, uint16_t supervision_timeout) {
749     TRY_POSTING_ON_MAIN(interface_.on_connection_update, ToLegacyHciErrorCode(hci_status), handle_,
750                         connection_interval, connection_latency, supervision_timeout);
751   }
OnParameterUpdateRequest(uint16_t interval_min,uint16_t interval_max,uint16_t latency,uint16_t supervision_timeout)752   void OnParameterUpdateRequest(uint16_t interval_min, uint16_t interval_max, uint16_t latency,
753                                 uint16_t supervision_timeout) {
754     TRY_POSTING_ON_MAIN(interface_.on_parameter_update_request, handle_, interval_min, interval_max,
755                         latency, supervision_timeout);
756   }
OnDataLengthChange(uint16_t max_tx_octets,uint16_t max_tx_time,uint16_t max_rx_octets,uint16_t max_rx_time)757   void OnDataLengthChange(uint16_t max_tx_octets, uint16_t max_tx_time, uint16_t max_rx_octets,
758                           uint16_t max_rx_time) {
759     TRY_POSTING_ON_MAIN(interface_.on_data_length_change, handle_, max_tx_octets, max_tx_time,
760                         max_rx_octets, max_rx_time);
761   }
OnLeSubrateChange(hci::ErrorCode hci_status,uint16_t subrate_factor,uint16_t peripheral_latency,uint16_t continuation_number,uint16_t supervision_timeout)762   void OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor,
763                          uint16_t peripheral_latency, uint16_t continuation_number,
764                          uint16_t supervision_timeout) {
765     TRY_POSTING_ON_MAIN(interface_.on_le_subrate_change, handle_, subrate_factor,
766                         peripheral_latency, continuation_number, supervision_timeout,
767                         ToLegacyHciErrorCode(hci_status));
768   }
769 
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)770   void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status, uint8_t lmp_version,
771                                               uint16_t manufacturer_name,
772                                               uint16_t sub_version) override {
773     TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete,
774                         ToLegacyHciErrorCode(hci_status), handle_, lmp_version, manufacturer_name,
775                         sub_version);
776   }
777 
OnLeReadRemoteFeaturesComplete(hci::ErrorCode,uint64_t)778   void OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status */, uint64_t /* features */) {
779     // TODO
780   }
781 
OnPhyUpdate(hci::ErrorCode hci_status,uint8_t tx_phy,uint8_t rx_phy)782   void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy) override {
783     TRY_POSTING_ON_MAIN(interface_.on_phy_update, ToLegacyHciErrorCode(hci_status), handle_, tx_phy,
784                         rx_phy);
785   }
786 
OnDisconnection(hci::ErrorCode reason)787   void OnDisconnection(hci::ErrorCode reason) {
788     Disconnect();
789     on_disconnect_(handle_, reason);
790   }
791 
GetRemoteAddressWithType() const792   hci::AddressWithType GetRemoteAddressWithType() const { return connection_->GetRemoteAddress(); }
793 
InitiateDisconnect(hci::DisconnectReason reason)794   void InitiateDisconnect(hci::DisconnectReason reason) override {
795     connection_->Disconnect(reason);
796   }
797 
IsLocallyInitiated() const798   bool IsLocallyInitiated() const override { return connection_->locally_initiated_; }
799 
IsInFilterAcceptList() const800   bool IsInFilterAcceptList() const { return connection_->IsInFilterAcceptList(); }
801 
UpdateConnectionParameters(uint16_t conn_int_min,uint16_t conn_int_max,uint16_t conn_latency,uint16_t conn_timeout,uint16_t min_ce_len,uint16_t max_ce_len)802   void UpdateConnectionParameters(uint16_t conn_int_min, uint16_t conn_int_max,
803                                   uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len,
804                                   uint16_t max_ce_len) {
805     connection_->LeConnectionUpdate(conn_int_min, conn_int_max, conn_latency, conn_timeout,
806                                     min_ce_len, max_ce_len);
807   }
808 
809 private:
810   OnDisconnect on_disconnect_;
811   const shim::acl_le_link_interface_t interface_;
812   std::unique_ptr<hci::acl_manager::LeAclConnection> connection_;
813 };
814 
815 struct shim::Acl::impl {
implshim::Acl::impl816   impl(uint8_t max_address_resolution_size)
817       : shadow_address_resolution_list_(ShadowAddressResolutionList(max_address_resolution_size)) {}
818 
819   std::map<HciHandle, std::unique_ptr<ClassicShimAclConnection>> handle_to_classic_connection_map_;
820   std::map<HciHandle, std::unique_ptr<LeShimAclConnection>> handle_to_le_connection_map_;
821 
822   SyncMapCount<std::string> classic_acl_disconnect_reason_;
823   SyncMapCount<std::string> le_acl_disconnect_reason_;
824 
825   FixedQueue<std::unique_ptr<ConnectionDescriptor>> connection_history_ =
826           FixedQueue<std::unique_ptr<ConnectionDescriptor>>(kConnectionHistorySize);
827 
828   ShadowAddressResolutionList shadow_address_resolution_list_;
829 
830   struct timed_wakelock wakeup_wakelock_;
831   bool system_suspend_ = false;
832 
IsClassicAclshim::Acl::impl833   bool IsClassicAcl(HciHandle handle) {
834     return handle_to_classic_connection_map_.find(handle) !=
835            handle_to_classic_connection_map_.end();
836   }
837 
EnqueueClassicPacketshim::Acl::impl838   void EnqueueClassicPacket(HciHandle handle, std::unique_ptr<packet::RawBuilder> packet) {
839     log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle);
840     handle_to_classic_connection_map_[handle]->EnqueuePacket(std::move(packet));
841   }
842 
Flushshim::Acl::impl843   void Flush(HciHandle handle) {
844     if (IsClassicAcl(handle)) {
845       handle_to_classic_connection_map_[handle]->Flush();
846     } else {
847       log::error("handle {} is not a classic connection", handle);
848     }
849   }
850 
IsLeAclshim::Acl::impl851   bool IsLeAcl(HciHandle handle) {
852     return handle_to_le_connection_map_.find(handle) != handle_to_le_connection_map_.end();
853   }
854 
EnqueueLePacketshim::Acl::impl855   void EnqueueLePacket(HciHandle handle, std::unique_ptr<packet::RawBuilder> packet) {
856     log::assert_that(IsLeAcl(handle), "handle {} is not a LE connection", handle);
857     handle_to_le_connection_map_[handle]->EnqueuePacket(std::move(packet));
858   }
859 
DisconnectClassicConnectionsshim::Acl::impl860   void DisconnectClassicConnections(std::promise<void> promise) {
861     log::info("Disconnect gd acl shim classic connections");
862     std::vector<HciHandle> disconnect_handles;
863     for (auto& connection : handle_to_classic_connection_map_) {
864       disconnect_classic(connection.first, HCI_ERR_REMOTE_POWER_OFF, "Suspend disconnect");
865       disconnect_handles.push_back(connection.first);
866     }
867 
868 #ifndef TARGET_FLOSS
869     // Since this is a suspend disconnect, we immediately also call
870     // |OnClassicSuspendInitiatedDisconnect| without waiting for it to happen.
871     // We want the stack to clean up ahead of the link layer (since we will mask
872     // away that event). The reason we do this in a separate loop is that this
873     // will also remove the handle from the connection map.
874     for (auto& handle : disconnect_handles) {
875       auto found = handle_to_classic_connection_map_.find(handle);
876       if (found != handle_to_classic_connection_map_.end()) {
877         GetAclManager()->OnClassicSuspendInitiatedDisconnect(
878                 found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST);
879       }
880     }
881 #endif
882     promise.set_value();
883   }
884 
ShutdownClassicConnectionsshim::Acl::impl885   void ShutdownClassicConnections(std::promise<void> promise) {
886     log::info("Shutdown gd acl shim classic connections");
887     for (auto& connection : handle_to_classic_connection_map_) {
888       connection.second->Shutdown();
889     }
890     handle_to_classic_connection_map_.clear();
891     promise.set_value();
892   }
893 
DisconnectLeConnectionsshim::Acl::impl894   void DisconnectLeConnections(std::promise<void> promise) {
895     log::info("Disconnect gd acl shim le connections");
896     std::vector<HciHandle> disconnect_handles;
897     for (auto& connection : handle_to_le_connection_map_) {
898       disconnect_le(connection.first, HCI_ERR_REMOTE_POWER_OFF, "Suspend disconnect");
899       disconnect_handles.push_back(connection.first);
900     }
901 
902 #ifndef TARGET_FLOSS
903     // Since this is a suspend disconnect, we immediately also call
904     // |OnLeSuspendInitiatedDisconnect| without waiting for it to happen. We
905     // want the stack to clean up ahead of the link layer (since we will mask
906     // away that event). The reason we do this in a separate loop is that this
907     // will also remove the handle from the connection map.
908     for (auto& handle : disconnect_handles) {
909       auto found = handle_to_le_connection_map_.find(handle);
910       if (found != handle_to_le_connection_map_.end()) {
911         GetAclManager()->OnLeSuspendInitiatedDisconnect(
912                 found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST);
913       }
914     }
915 #endif
916     promise.set_value();
917   }
918 
ShutdownLeConnectionsshim::Acl::impl919   void ShutdownLeConnections(std::promise<void> promise) {
920     log::info("Shutdown gd acl shim le connections");
921     for (auto& connection : handle_to_le_connection_map_) {
922       connection.second->Shutdown();
923     }
924     handle_to_le_connection_map_.clear();
925     promise.set_value();
926   }
927 
FinalShutdownshim::Acl::impl928   void FinalShutdown(std::promise<void> promise) {
929     if (!handle_to_classic_connection_map_.empty()) {
930       for (auto& connection : handle_to_classic_connection_map_) {
931         connection.second->Shutdown();
932       }
933       handle_to_classic_connection_map_.clear();
934       log::info("Cleared all classic connections count:{}",
935                 handle_to_classic_connection_map_.size());
936     }
937 
938     if (!handle_to_le_connection_map_.empty()) {
939       for (auto& connection : handle_to_le_connection_map_) {
940         connection.second->Shutdown();
941       }
942       handle_to_le_connection_map_.clear();
943       log::info("Cleared all le connections count:{}", handle_to_le_connection_map_.size());
944     }
945     promise.set_value();
946   }
947 
HoldModeshim::Acl::impl948   void HoldMode(HciHandle handle, uint16_t max_interval, uint16_t min_interval) {
949     log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle);
950     handle_to_classic_connection_map_[handle]->HoldMode(max_interval, min_interval);
951   }
952 
ExitSniffModeshim::Acl::impl953   void ExitSniffMode(HciHandle handle) {
954     log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle);
955     handle_to_classic_connection_map_[handle]->ExitSniffMode();
956   }
957 
SniffModeshim::Acl::impl958   void SniffMode(HciHandle handle, uint16_t max_interval, uint16_t min_interval, uint16_t attempt,
959                  uint16_t timeout) {
960     log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle);
961     handle_to_classic_connection_map_[handle]->SniffMode(max_interval, min_interval, attempt,
962                                                          timeout);
963   }
964 
SniffSubratingshim::Acl::impl965   void SniffSubrating(HciHandle handle, uint16_t maximum_latency, uint16_t minimum_remote_timeout,
966                       uint16_t minimum_local_timeout) {
967     log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle);
968     handle_to_classic_connection_map_[handle]->SniffSubrating(
969             maximum_latency, minimum_remote_timeout, minimum_local_timeout);
970   }
971 
LeSubrateRequestshim::Acl::impl972   void LeSubrateRequest(HciHandle handle, uint16_t subrate_min, uint16_t subrate_max,
973                         uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) {
974     if (IsLeAcl(handle)) {
975       handle_to_le_connection_map_[handle]->LeSubrateRequest(subrate_min, subrate_max, max_latency,
976                                                              cont_num, sup_tout);
977     } else {
978       log::info("handle {} is not a LE connection", handle);
979     }
980   }
981 
SetConnectionEncryptionshim::Acl::impl982   void SetConnectionEncryption(HciHandle handle, hci::Enable enable) {
983     log::assert_that(IsClassicAcl(handle), "handle {} is not a classic connection", handle);
984     handle_to_classic_connection_map_[handle]->SetConnectionEncryption(enable);
985   }
986 
disconnect_classicshim::Acl::impl987   void disconnect_classic(uint16_t handle, tHCI_STATUS reason, std::string comment) {
988     auto connection = handle_to_classic_connection_map_.find(handle);
989     if (connection != handle_to_classic_connection_map_.end()) {
990       auto remote_address = connection->second->GetRemoteAddress();
991       connection->second->InitiateDisconnect(ToDisconnectReasonFromLegacy(reason));
992       log::debug("Disconnection initiated classic remote:{} handle:{}", remote_address, handle);
993       BTM_LogHistory(
994               kBtmLogTag, ToRawAddress(remote_address), "Disconnection initiated",
995               std::format("classic reason:{} comment:{}", hci_status_code_text(reason), comment));
996       classic_acl_disconnect_reason_.Put(comment);
997     } else {
998       log::warn("Unable to disconnect unknown classic connection handle:0x{:04x}", handle);
999     }
1000   }
1001 
disconnect_leshim::Acl::impl1002   void disconnect_le(uint16_t handle, tHCI_STATUS reason, std::string comment) {
1003     auto connection = handle_to_le_connection_map_.find(handle);
1004     if (connection != handle_to_le_connection_map_.end()) {
1005       auto remote_address_with_type = connection->second->GetRemoteAddressWithType();
1006       GetAclManager()->RemoveFromBackgroundList(remote_address_with_type);
1007       connection->second->InitiateDisconnect(ToDisconnectReasonFromLegacy(reason));
1008       log::debug("Disconnection initiated le remote:{} handle:{}", remote_address_with_type,
1009                  handle);
1010       BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type),
1011                      "Disconnection initiated",
1012                      std::format("Le reason:{} comment:{}", hci_status_code_text(reason), comment));
1013       le_acl_disconnect_reason_.Put(comment);
1014     } else {
1015       log::warn("Unable to disconnect unknown le connection handle:0x{:04x}", handle);
1016     }
1017   }
1018 
update_connection_parametersshim::Acl::impl1019   void update_connection_parameters(uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max,
1020                                     uint16_t conn_latency, uint16_t conn_timeout,
1021                                     uint16_t min_ce_len, uint16_t max_ce_len) {
1022     auto connection = handle_to_le_connection_map_.find(handle);
1023     if (connection == handle_to_le_connection_map_.end()) {
1024       log::warn("Unknown le connection handle:0x{:04x}", handle);
1025       return;
1026     }
1027     connection->second->UpdateConnectionParameters(conn_int_min, conn_int_max, conn_latency,
1028                                                    conn_timeout, min_ce_len, max_ce_len);
1029   }
1030 
get_connection_local_addressshim::Acl::impl1031   void get_connection_local_address(uint16_t handle, bool ota_address,
1032                                     std::promise<bluetooth::hci::AddressWithType> promise) {
1033     log::debug("get_connection_local_address handle:{} ota_address:{}", handle, ota_address);
1034     bluetooth::hci::AddressWithType address_with_type;
1035     for (auto& [acl_handle, connection] : handle_to_le_connection_map_) {
1036       if (acl_handle != handle) {
1037         continue;
1038       }
1039 
1040       if (ota_address) {
1041         promise.set_value(connection->GetLocalOtaAddressWithType());
1042         return;
1043       }
1044       promise.set_value(connection->GetLocalAddressWithType());
1045       return;
1046     }
1047     log::warn("address not found!");
1048     promise.set_value(address_with_type);
1049     return;
1050   }
1051 
get_connection_peer_addressshim::Acl::impl1052   void get_connection_peer_address(uint16_t handle, bool ota_address,
1053                                    std::promise<bluetooth::hci::AddressWithType> promise) {
1054     log::debug("get_connection_peer_address handle:{} ota_address:{}", handle, ota_address);
1055     bluetooth::hci::AddressWithType address_with_type;
1056     for (auto& [acl_handle, connection] : handle_to_le_connection_map_) {
1057       if (acl_handle != handle) {
1058         continue;
1059       }
1060 
1061       if (ota_address) {
1062         promise.set_value(connection->GetPeerOtaAddressWithType());
1063         return;
1064       }
1065       promise.set_value(connection->GetPeerAddressWithType());
1066       return;
1067     }
1068     log::warn("address not found!");
1069     promise.set_value(address_with_type);
1070     return;
1071   }
1072 
get_advertising_set_connected_toshim::Acl::impl1073   void get_advertising_set_connected_to(const RawAddress& remote_bda,
1074                                         std::promise<std::optional<uint8_t>> promise) {
1075     log::debug("get_advertising_set_connected_to {}", remote_bda);
1076     auto remote_address = ToGdAddress(remote_bda);
1077     for (auto& [handle, connection] : handle_to_le_connection_map_) {
1078       if (connection->GetRemoteAddressWithType().GetAddress() == remote_address) {
1079         promise.set_value(connection->GetAdvertisingSetConnectedTo());
1080         return;
1081       }
1082     }
1083     log::warn("address not found!");
1084     promise.set_value({});
1085     return;
1086   }
1087 
clear_acceptlistshim::Acl::impl1088   void clear_acceptlist() { GetAclManager()->ClearFilterAcceptList(); }
1089 
AddToAddressResolutionshim::Acl::impl1090   void AddToAddressResolution(const hci::AddressWithType& address_with_type,
1091                               const std::array<uint8_t, 16>& peer_irk,
1092                               const std::array<uint8_t, 16>& local_irk) {
1093     if (shadow_address_resolution_list_.IsFull()) {
1094       log::warn("Le Address Resolution list is full size:{}",
1095                 shadow_address_resolution_list_.Size());
1096       return;
1097     }
1098     // TODO This should really be added upon successful completion
1099     shadow_address_resolution_list_.Add(address_with_type);
1100     GetAclManager()->AddDeviceToResolvingList(address_with_type, peer_irk, local_irk);
1101   }
1102 
RemoveFromAddressResolutionshim::Acl::impl1103   void RemoveFromAddressResolution(const hci::AddressWithType& address_with_type) {
1104     // TODO This should really be removed upon successful removal
1105     if (!shadow_address_resolution_list_.Remove(address_with_type)) {
1106       log::warn("Unable to remove from Le Address Resolution list device:{}", address_with_type);
1107     }
1108     GetAclManager()->RemoveDeviceFromResolvingList(address_with_type);
1109   }
1110 
ClearResolvingListshim::Acl::impl1111   void ClearResolvingList() {
1112     GetAclManager()->ClearResolvingList();
1113     // TODO This should really be cleared after successful clear status
1114     shadow_address_resolution_list_.Clear();
1115   }
1116 
SetSystemSuspendStateshim::Acl::impl1117   void SetSystemSuspendState(bool suspended) { GetAclManager()->SetSystemSuspendState(suspended); }
1118 
DumpConnectionHistoryshim::Acl::impl1119   void DumpConnectionHistory() const {
1120     std::vector<std::string> history = connection_history_.ReadElementsAsString();
1121     for (auto& entry : history) {
1122       log::debug("{}", entry);
1123     }
1124   }
1125 
1126 #define DUMPSYS_TAG "shim::acl"
DumpConnectionHistoryshim::Acl::impl1127   void DumpConnectionHistory(int fd) const {
1128     std::vector<std::string> history = connection_history_.ReadElementsAsString();
1129     for (auto& entry : history) {
1130       LOG_DUMPSYS(fd, "%s", entry.c_str());
1131     }
1132     if (classic_acl_disconnect_reason_.Size() > 0) {
1133       LOG_DUMPSYS(fd, "Classic sources of initiated disconnects");
1134       for (const auto& item : classic_acl_disconnect_reason_.GetSortedHighToLow()) {
1135         LOG_DUMPSYS(fd, "  %s:%zu", item.item.c_str(), item.count);
1136       }
1137     }
1138     if (le_acl_disconnect_reason_.Size() > 0) {
1139       LOG_DUMPSYS(fd, "Le sources of initiated disconnects");
1140       for (const auto& item : le_acl_disconnect_reason_.GetSortedHighToLow()) {
1141         LOG_DUMPSYS(fd, "  %s:%zu", item.item.c_str(), item.count);
1142       }
1143     }
1144 
1145     auto address_resolution_list = shadow_address_resolution_list_.GetCopy();
1146     LOG_DUMPSYS(fd,
1147                 "Shadow le address resolution list  size:%-3zu "
1148                 "controller_max_size:%hhu",
1149                 address_resolution_list.size(), shadow_address_resolution_list_.GetMaxSize());
1150     unsigned cnt = 0;
1151     for (auto& entry : address_resolution_list) {
1152       LOG_DUMPSYS(fd, "  %03u %s", ++cnt, entry.ToRedactedStringForLogging().c_str());
1153     }
1154   }
1155 #undef DUMPSYS_TAG
1156 };
1157 
1158 #define DUMPSYS_TAG "shim::acl"
DumpsysAcl(int fd)1159 void DumpsysAcl(int fd) {
1160   const tACL_CB& acl_cb = btm_cb.acl_cb_;
1161 
1162   LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1163 
1164   if (shim::Stack::GetInstance()->IsRunning()) {
1165     shim::Stack::GetInstance()->GetAcl()->DumpConnectionHistory(fd);
1166   }
1167 
1168   for (int i = 0; i < MAX_L2CAP_LINKS; i++) {
1169     const tACL_CONN& link = acl_cb.acl_db[i];
1170     if (!link.in_use) {
1171       continue;
1172     }
1173 
1174     LOG_DUMPSYS(fd, "remote_addr:%s handle:0x%04x transport:%s",
1175                 link.remote_addr.ToRedactedStringForLogging().c_str(), link.hci_handle,
1176                 bt_transport_text(link.transport).c_str());
1177     LOG_DUMPSYS(fd, "    link_up_issued:%5s", (link.link_up_issued) ? "true" : "false");
1178     LOG_DUMPSYS(fd, "    flush_timeout:0x%04x", link.flush_timeout_in_ticks);
1179     LOG_DUMPSYS(fd, "    link_supervision_timeout:%.3f sec",
1180                 ticks_to_seconds(link.link_super_tout));
1181     LOG_DUMPSYS(fd, "    disconnect_reason:0x%02x", link.disconnect_reason);
1182 
1183     if (link.is_transport_br_edr()) {
1184       for (int j = 0; j < HCI_EXT_FEATURES_PAGE_MAX + 1; j++) {
1185         if (!link.peer_lmp_feature_valid[j]) {
1186           continue;
1187         }
1188         LOG_DUMPSYS(fd, "    peer_lmp_features[%d] valid:%s data:%s", j,
1189                     common::ToString(link.peer_lmp_feature_valid[j]).c_str(),
1190                     bd_features_text(link.peer_lmp_feature_pages[j]).c_str());
1191       }
1192       LOG_DUMPSYS(fd, "    [classic] link_policy:%s",
1193                   link_policy_text(static_cast<tLINK_POLICY>(link.link_policy)).c_str());
1194       LOG_DUMPSYS(fd, "    [classic] sniff_subrating:%s",
1195                   common::ToString(HCI_SNIFF_SUB_RATE_SUPPORTED(link.peer_lmp_feature_pages[0]))
1196                           .c_str());
1197 
1198       LOG_DUMPSYS(fd, "    pkt_types_mask:0x%04x", link.pkt_types_mask);
1199       LOG_DUMPSYS(fd, "    role:%s", RoleText(link.link_role).c_str());
1200     } else if (link.is_transport_ble()) {
1201       LOG_DUMPSYS(fd, "    [le] peer_features valid:%s data:%s",
1202                   common::ToString(link.peer_le_features_valid).c_str(),
1203                   bd_features_text(link.peer_le_features).c_str());
1204 
1205       LOG_DUMPSYS(fd, "    [le] active_remote_addr:%s[%s]",
1206                   link.active_remote_addr.ToRedactedStringForLogging().c_str(),
1207                   AddressTypeText(link.active_remote_addr_type).c_str());
1208     }
1209   }
1210 }
1211 #undef DUMPSYS_TAG
1212 
1213 #define DUMPSYS_TAG "shim::stack"
DumpsysNeighbor(int fd)1214 void DumpsysNeighbor(int fd) {
1215   LOG_DUMPSYS(fd, "Stack information %lc%lc", kRunicBjarkan, kRunicHagall);
1216   if (btm_cb.neighbor.classic_inquiry.start_time_ms == 0) {
1217     LOG_DUMPSYS(fd, "Classic inquiry:disabled");
1218   } else {
1219     LOG_DUMPSYS(fd, "Classic inquiry:enabled duration_s:%.3f results:%lu",
1220                 (timestamper_in_milliseconds.GetTimestamp() -
1221                  btm_cb.neighbor.classic_inquiry.start_time_ms) /
1222                         1000.0,
1223                 (unsigned long)btm_cb.neighbor.classic_inquiry.results);
1224   }
1225   if (btm_cb.neighbor.le_scan.start_time_ms == 0) {
1226     LOG_DUMPSYS(fd, "Le scan:disabled");
1227   } else {
1228     LOG_DUMPSYS(
1229             fd, "Le scan:enabled duration_s:%.3f results:%lu",
1230             (timestamper_in_milliseconds.GetTimestamp() - btm_cb.neighbor.le_scan.start_time_ms) /
1231                     1000.0,
1232             (unsigned long)btm_cb.neighbor.le_scan.results);
1233   }
1234   const auto copy = btm_cb.neighbor.inquiry_history_->Pull();
1235   LOG_DUMPSYS(fd, "Last %zu inquiry scans:", copy.size());
1236   for (const auto& it : copy) {
1237     LOG_DUMPSYS(fd,
1238                 "  %s - %s duration_ms:%-5llu num_resp:%-2u"
1239                 " std:%-2u rssi:%-2u ext:%-2u %12s",
1240                 EpochMillisToString(it.entry.start_time_ms).c_str(),
1241                 EpochMillisToString(it.timestamp).c_str(),
1242                 (unsigned long long)(it.timestamp - it.entry.start_time_ms), it.entry.num_resp,
1243                 it.entry.resp_type[BTM_INQ_RESULT_STANDARD],
1244                 it.entry.resp_type[BTM_INQ_RESULT_WITH_RSSI],
1245                 it.entry.resp_type[BTM_INQ_RESULT_EXTENDED],
1246                 btm_inquiry_cmpl_status_text(it.entry.status).c_str());
1247   }
1248 }
1249 #undef DUMPSYS_TAG
1250 
Dump(int fd) const1251 void shim::Acl::Dump(int fd) const {
1252   DumpsysNeighbor(fd);
1253   DumpsysAcl(fd);
1254 }
1255 
Acl(os::Handler * handler,const acl_interface_t & acl_interface,uint8_t max_address_resolution_size)1256 shim::Acl::Acl(os::Handler* handler, const acl_interface_t& acl_interface,
1257                uint8_t max_address_resolution_size)
1258     : handler_(handler), acl_interface_(acl_interface) {
1259   log::assert_that(handler_ != nullptr, "assert failed: handler_ != nullptr");
1260   ValidateAclInterface(acl_interface_);
1261   pimpl_ = std::make_unique<Acl::impl>(max_address_resolution_size);
1262   GetAclManager()->RegisterCallbacks(this, handler_);
1263   GetAclManager()->RegisterLeCallbacks(this, handler_);
1264   GetController()->RegisterCompletedMonitorAclPacketsCallback(
1265           handler->BindOn(this, &Acl::on_incoming_acl_credits));
1266   shim::RegisterDumpsysFunction(static_cast<void*>(this), [this](int fd) { Dump(fd); });
1267 }
1268 
~Acl()1269 shim::Acl::~Acl() {
1270   shim::UnregisterDumpsysFunction(static_cast<void*>(this));
1271   GetController()->UnregisterCompletedMonitorAclPacketsCallback();
1272 
1273   if (CheckForOrphanedAclConnections()) {
1274     pimpl_->DumpConnectionHistory();
1275   }
1276 }
1277 
CheckForOrphanedAclConnections() const1278 bool shim::Acl::CheckForOrphanedAclConnections() const {
1279   bool orphaned_acl_connections = false;
1280 
1281   if (!pimpl_->handle_to_classic_connection_map_.empty()) {
1282     log::error("About to destroy classic active ACL");
1283     for (const auto& connection : pimpl_->handle_to_classic_connection_map_) {
1284       log::error("Orphaned classic ACL handle:0x{:04x} bd_addr:{} created:{}",
1285                  connection.second->Handle(), connection.second->GetRemoteAddress(),
1286                  common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat,
1287                                                           connection.second->GetCreationTime()));
1288     }
1289     orphaned_acl_connections = true;
1290   }
1291 
1292   if (!pimpl_->handle_to_le_connection_map_.empty()) {
1293     log::error("About to destroy le active ACL");
1294     for (const auto& connection : pimpl_->handle_to_le_connection_map_) {
1295       log::error("Orphaned le ACL handle:0x{:04x} bd_addr:{} created:{}",
1296                  connection.second->Handle(), connection.second->GetRemoteAddressWithType(),
1297                  common::StringFormatTimeWithMilliseconds(kConnectionDescriptorTimeFormat,
1298                                                           connection.second->GetCreationTime()));
1299     }
1300     orphaned_acl_connections = true;
1301   }
1302   return orphaned_acl_connections;
1303 }
1304 
on_incoming_acl_credits(uint16_t handle,uint16_t credits)1305 void shim::Acl::on_incoming_acl_credits(uint16_t handle, uint16_t credits) {
1306   TRY_POSTING_ON_MAIN(acl_interface_.on_packets_completed, handle, credits);
1307 }
1308 
write_data_sync(HciHandle handle,std::unique_ptr<packet::RawBuilder> packet)1309 void shim::Acl::write_data_sync(HciHandle handle, std::unique_ptr<packet::RawBuilder> packet) {
1310   if (pimpl_->IsClassicAcl(handle)) {
1311     pimpl_->EnqueueClassicPacket(handle, std::move(packet));
1312   } else if (pimpl_->IsLeAcl(handle)) {
1313     pimpl_->EnqueueLePacket(handle, std::move(packet));
1314   } else {
1315     log::error("Unable to find destination to write data\n");
1316   }
1317 }
1318 
WriteData(HciHandle handle,std::unique_ptr<packet::RawBuilder> packet)1319 void shim::Acl::WriteData(HciHandle handle, std::unique_ptr<packet::RawBuilder> packet) {
1320   handler_->Post(common::BindOnce(&Acl::write_data_sync, common::Unretained(this), handle,
1321                                   std::move(packet)));
1322 }
1323 
flush(HciHandle handle)1324 void shim::Acl::flush(HciHandle handle) { pimpl_->Flush(handle); }
1325 
Flush(HciHandle handle)1326 void shim::Acl::Flush(HciHandle handle) {
1327   handler_->Post(common::BindOnce(&Acl::flush, common::Unretained(this), handle));
1328 }
1329 
CreateClassicConnection(const hci::Address & address)1330 void shim::Acl::CreateClassicConnection(const hci::Address& address) {
1331   GetAclManager()->CreateConnection(address);
1332   log::debug("Connection initiated for classic to remote:{}", address);
1333   BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Initiated connection", "classic");
1334 }
1335 
CancelClassicConnection(const hci::Address & address)1336 void shim::Acl::CancelClassicConnection(const hci::Address& address) {
1337   GetAclManager()->CancelConnect(address);
1338   log::debug("Connection cancelled for classic to remote:{}", address);
1339   BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Cancelled connection", "classic");
1340 }
1341 
OnClassicLinkDisconnected(HciHandle handle,hci::ErrorCode reason)1342 void shim::Acl::OnClassicLinkDisconnected(HciHandle handle, hci::ErrorCode reason) {
1343   hci::Address remote_address =
1344           pimpl_->handle_to_classic_connection_map_[handle]->GetRemoteAddress();
1345   CreationTime creation_time = pimpl_->handle_to_classic_connection_map_[handle]->GetCreationTime();
1346   bool is_locally_initiated =
1347           pimpl_->handle_to_classic_connection_map_[handle]->IsLocallyInitiated();
1348 
1349   TeardownTime teardown_time = std::chrono::system_clock::now();
1350 
1351   bluetooth::metrics::LogAclDisconnectionEvent(remote_address, reason, is_locally_initiated);
1352 
1353   pimpl_->handle_to_classic_connection_map_.erase(handle);
1354   TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_disconnected,
1355                       ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
1356                       ToLegacyHciErrorCode(reason));
1357   log::debug("Disconnected classic link remote:{} handle:{} reason:{}", remote_address, handle,
1358              ErrorCodeText(reason));
1359   BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address), "Disconnected",
1360                  std::format("classic reason:{}", ErrorCodeText(reason)));
1361   pimpl_->connection_history_.Push(std::make_unique<ClassicConnectionDescriptor>(
1362           remote_address, creation_time, teardown_time, handle, is_locally_initiated, reason));
1363 }
1364 
GetConnectionLocalAddress(uint16_t handle,bool ota_address,std::promise<bluetooth::hci::AddressWithType> promise)1365 void shim::Acl::GetConnectionLocalAddress(
1366         uint16_t handle, bool ota_address, std::promise<bluetooth::hci::AddressWithType> promise) {
1367   log::debug("GetConnectionLocalAddress handle:{} ota_address:{}", handle, ota_address);
1368   handler_->CallOn(pimpl_.get(), &Acl::impl::get_connection_local_address, handle, ota_address,
1369                    std::move(promise));
1370 }
1371 
GetConnectionPeerAddress(uint16_t handle,bool ota_address,std::promise<bluetooth::hci::AddressWithType> promise)1372 void shim::Acl::GetConnectionPeerAddress(
1373         uint16_t handle, bool ota_address, std::promise<bluetooth::hci::AddressWithType> promise) {
1374   log::debug("GetConnectionPeerAddress handle:{} ota_address:{}", handle, ota_address);
1375   handler_->CallOn(pimpl_.get(), &Acl::impl::get_connection_peer_address, handle, ota_address,
1376                    std::move(promise));
1377 }
1378 
GetAdvertisingSetConnectedTo(const RawAddress & remote_bda,std::promise<std::optional<uint8_t>> promise)1379 void shim::Acl::GetAdvertisingSetConnectedTo(const RawAddress& remote_bda,
1380                                                      std::promise<std::optional<uint8_t>> promise) {
1381   log::debug("GetAdvertisingSetConnectedTo {}", remote_bda);
1382   handler_->CallOn(pimpl_.get(), &Acl::impl::get_advertising_set_connected_to, remote_bda,
1383                    std::move(promise));
1384 }
1385 
OnLeLinkDisconnected(HciHandle handle,hci::ErrorCode reason)1386 void shim::Acl::OnLeLinkDisconnected(HciHandle handle, hci::ErrorCode reason) {
1387   hci::AddressWithType remote_address_with_type =
1388           pimpl_->handle_to_le_connection_map_[handle]->GetRemoteAddressWithType();
1389   CreationTime creation_time = pimpl_->handle_to_le_connection_map_[handle]->GetCreationTime();
1390   bool is_locally_initiated = pimpl_->handle_to_le_connection_map_[handle]->IsLocallyInitiated();
1391 
1392   TeardownTime teardown_time = std::chrono::system_clock::now();
1393 
1394   pimpl_->handle_to_le_connection_map_.erase(handle);
1395   TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_disconnected,
1396                       ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
1397                       ToLegacyHciErrorCode(reason));
1398   log::debug("Disconnected le link remote:{} handle:{} reason:{}", remote_address_with_type, handle,
1399              ErrorCodeText(reason));
1400   BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type), "Disconnected",
1401                  std::format("Le reason:{}", ErrorCodeText(reason)));
1402   pimpl_->connection_history_.Push(std::make_unique<LeConnectionDescriptor>(
1403           remote_address_with_type, creation_time, teardown_time, handle, is_locally_initiated,
1404           reason));
1405 }
1406 
OnConnectSuccess(std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection)1407 void shim::Acl::OnConnectSuccess(
1408         std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection) {
1409   log::assert_that(connection != nullptr, "assert failed: connection != nullptr");
1410   auto handle = connection->GetHandle();
1411   bool locally_initiated = connection->locally_initiated_;
1412   const hci::Address remote_address = connection->GetAddress();
1413   const RawAddress bd_addr = ToRawAddress(remote_address);
1414 
1415   pimpl_->handle_to_classic_connection_map_.emplace(
1416           handle, std::make_unique<ClassicShimAclConnection>(
1417                           acl_interface_.on_send_data_upwards,
1418                           std::bind(&shim::Acl::OnClassicLinkDisconnected, this,
1419                                     std::placeholders::_1, std::placeholders::_2),
1420                           acl_interface_.link.classic, handler_, std::move(connection),
1421                           std::chrono::system_clock::now()));
1422   pimpl_->handle_to_classic_connection_map_[handle]->RegisterCallbacks();
1423   pimpl_->handle_to_classic_connection_map_[handle]->ReadRemoteControllerInformation();
1424 
1425   TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connected, bd_addr, handle, false,
1426                       locally_initiated);
1427   log::debug("Connection successful classic remote:{} handle:{} initiator:{}", remote_address,
1428              handle, (locally_initiated) ? "local" : "remote");
1429   metrics::LogAclCompletionEvent(remote_address, hci::ErrorCode::SUCCESS, locally_initiated);
1430   BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address), "Connection successful",
1431                  (locally_initiated) ? "classic Local initiated" : "classic Remote initiated");
1432 }
1433 
OnConnectRequest(hci::Address address,hci::ClassOfDevice cod)1434 void shim::Acl::OnConnectRequest(hci::Address address, hci::ClassOfDevice cod) {
1435   const RawAddress bd_addr = ToRawAddress(address);
1436   const DEV_CLASS dev_class = ToDevClass(cod);
1437 
1438   if (com::android::bluetooth::flags::adapter_suspend_mgmt()) {
1439     if (pimpl_->system_suspend_) {
1440       pimpl_->wakeup_wakelock_.acquire(
1441               (uint64_t)osi_property_get_int32(kWakelockTimeoutMsSysprop, 0));
1442     }
1443   }
1444 
1445   TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connect_request, bd_addr, cod);
1446   log::debug("Received connect request remote:{} gd_cod:{} legacy_dev_class:{}", address,
1447              cod.ToString(), dev_class_text(dev_class));
1448   BTM_LogHistory(
1449           kBtmLogTag, ToRawAddress(address), "Connection request",
1450           std::format("gd_cod:{} legacy_dev_class:{}", cod.ToString(), dev_class_text(dev_class)));
1451 }
1452 
OnConnectFail(hci::Address address,hci::ErrorCode reason,bool locally_initiated)1453 void shim::Acl::OnConnectFail(hci::Address address, hci::ErrorCode reason, bool locally_initiated) {
1454   const RawAddress bd_addr = ToRawAddress(address);
1455   TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_failed, bd_addr,
1456                       ToLegacyHciErrorCode(reason), locally_initiated);
1457   log::warn("Connection failed classic remote:{} reason:{}", address, hci::ErrorCodeText(reason));
1458   metrics::LogAclCompletionEvent(address, reason, locally_initiated);
1459   BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection failed",
1460                  std::format("classic reason:{}", hci::ErrorCodeText(reason)));
1461 }
1462 
OnLeConnectSuccess(hci::AddressWithType address_with_type,std::unique_ptr<hci::acl_manager::LeAclConnection> connection)1463 void shim::Acl::OnLeConnectSuccess(hci::AddressWithType address_with_type,
1464                                    std::unique_ptr<hci::acl_manager::LeAclConnection> connection) {
1465   log::assert_that(connection != nullptr, "assert failed: connection != nullptr");
1466   auto handle = connection->GetHandle();
1467 
1468   if (com::android::bluetooth::flags::adapter_suspend_mgmt()) {
1469     if (pimpl_->system_suspend_) {
1470       pimpl_->wakeup_wakelock_.acquire(
1471               (uint64_t)osi_property_get_int32(kWakelockTimeoutMsSysprop, 0));
1472     }
1473   }
1474 
1475   // Save the peer address, if any
1476   hci::AddressWithType peer_address_with_type = connection->peer_address_with_type_;
1477 
1478   hci::Role connection_role = connection->GetRole();
1479   bool locally_initiated = connection->locally_initiated_;
1480 
1481   uint16_t conn_interval = connection->interval_;
1482   uint16_t conn_latency = connection->latency_;
1483   uint16_t conn_timeout = connection->supervision_timeout_;
1484 
1485   RawAddress local_rpa = ToRawAddress(connection->local_resolvable_private_address_);
1486   RawAddress peer_rpa = ToRawAddress(connection->peer_resolvable_private_address_);
1487   tBLE_ADDR_TYPE peer_addr_type =
1488           (tBLE_ADDR_TYPE)connection->peer_address_with_type_.GetAddressType();
1489 
1490   auto can_read_discoverable_characteristics = std::visit(
1491           [&](auto&& data) {
1492             using T = std::decay_t<decltype(data)>;
1493             if constexpr (std::is_same_v<T, hci::acl_manager::DataAsPeripheral>) {
1494               return data.connected_to_discoverable;
1495             } else {
1496               // if we are the central, the peer can always see discoverable
1497               // characteristics
1498               return true;
1499             }
1500           },
1501           connection->GetRoleSpecificData());
1502 
1503   pimpl_->handle_to_le_connection_map_.emplace(
1504           handle, std::make_unique<LeShimAclConnection>(
1505                           acl_interface_.on_send_data_upwards,
1506                           std::bind(&shim::Acl::OnLeLinkDisconnected, this, std::placeholders::_1,
1507                                     std::placeholders::_2),
1508                           acl_interface_.link.le, handler_, std::move(connection),
1509                           std::chrono::system_clock::now()));
1510   pimpl_->handle_to_le_connection_map_[handle]->RegisterCallbacks();
1511 
1512   if (!pimpl_->handle_to_le_connection_map_[handle]->IsInFilterAcceptList() &&
1513       connection_role == hci::Role::CENTRAL) {
1514     pimpl_->handle_to_le_connection_map_[handle]->InitiateDisconnect(
1515             hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
1516     log::info("Disconnected ACL after connection canceled");
1517     BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Connection canceled",
1518                    "Le");
1519     return;
1520   }
1521 
1522   pimpl_->handle_to_le_connection_map_[handle]->ReadRemoteControllerInformation();
1523 
1524   tBLE_BD_ADDR legacy_address_with_type = ToLegacyAddressWithType(address_with_type);
1525 
1526   TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_connected, legacy_address_with_type, handle,
1527                       ToLegacyRole(connection_role), conn_interval, conn_latency, conn_timeout,
1528                       local_rpa, peer_rpa, peer_addr_type, can_read_discoverable_characteristics);
1529 
1530   log::debug("Connection successful le remote:{} handle:{} initiator:{}", address_with_type, handle,
1531              (locally_initiated) ? "local" : "remote");
1532   bluetooth::metrics::LogLeAclCompletionEvent(address_with_type.GetAddress(),
1533                                               hci::ErrorCode::SUCCESS, locally_initiated);
1534 
1535   BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Connection successful",
1536                  "Le");
1537 }
1538 
OnLeConnectFail(hci::AddressWithType address_with_type,hci::ErrorCode reason)1539 void shim::Acl::OnLeConnectFail(hci::AddressWithType address_with_type, hci::ErrorCode reason) {
1540   tBLE_BD_ADDR legacy_address_with_type = ToLegacyAddressWithType(address_with_type);
1541 
1542   uint16_t handle = 0;  /* TODO Unneeded */
1543   bool enhanced = true; /* TODO logging metrics only */
1544   tHCI_STATUS status = ToLegacyHciErrorCode(reason);
1545 
1546   TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_failed, legacy_address_with_type, handle,
1547                       enhanced, status);
1548 
1549   bluetooth::metrics::LogLeAclCompletionEvent(address_with_type.GetAddress(), reason, true);
1550   log::warn("Connection failed le remote:{}", address_with_type);
1551   BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type), "Connection failed",
1552                  std::format("le reason:{}", hci::ErrorCodeText(reason)));
1553 }
1554 
DisconnectClassic(uint16_t handle,tHCI_STATUS reason,std::string comment)1555 void shim::Acl::DisconnectClassic(uint16_t handle, tHCI_STATUS reason, std::string comment) {
1556   handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_classic, handle, reason, comment);
1557 }
1558 
DisconnectLe(uint16_t handle,tHCI_STATUS reason,std::string comment)1559 void shim::Acl::DisconnectLe(uint16_t handle, tHCI_STATUS reason, std::string comment) {
1560   handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_le, handle, reason, comment);
1561 }
1562 
UpdateConnectionParameters(uint16_t handle,uint16_t conn_int_min,uint16_t conn_int_max,uint16_t conn_latency,uint16_t conn_timeout,uint16_t min_ce_len,uint16_t max_ce_len)1563 void shim::Acl::UpdateConnectionParameters(uint16_t handle, uint16_t conn_int_min,
1564                                            uint16_t conn_int_max, uint16_t conn_latency,
1565                                            uint16_t conn_timeout, uint16_t min_ce_len,
1566                                            uint16_t max_ce_len) {
1567   handler_->CallOn(pimpl_.get(), &Acl::impl::update_connection_parameters, handle, conn_int_min,
1568                    conn_int_max, conn_latency, conn_timeout, min_ce_len, max_ce_len);
1569 }
1570 
LeSubrateRequest(uint16_t hci_handle,uint16_t subrate_min,uint16_t subrate_max,uint16_t max_latency,uint16_t cont_num,uint16_t sup_tout)1571 void shim::Acl::LeSubrateRequest(uint16_t hci_handle, uint16_t subrate_min, uint16_t subrate_max,
1572                                  uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) {
1573   handler_->CallOn(pimpl_.get(), &Acl::impl::LeSubrateRequest, hci_handle, subrate_min, subrate_max,
1574                    max_latency, cont_num, sup_tout);
1575 }
1576 
DumpConnectionHistory(int fd) const1577 void shim::Acl::DumpConnectionHistory(int fd) const { pimpl_->DumpConnectionHistory(fd); }
1578 
DisconnectAllForSuspend()1579 void shim::Acl::DisconnectAllForSuspend() {
1580   if (CheckForOrphanedAclConnections()) {
1581     std::promise<void> disconnect_promise;
1582     auto disconnect_future = disconnect_promise.get_future();
1583     handler_->CallOn(pimpl_.get(), &Acl::impl::DisconnectClassicConnections,
1584                      std::move(disconnect_promise));
1585     disconnect_future.wait();
1586 
1587     disconnect_promise = std::promise<void>();
1588 
1589     disconnect_future = disconnect_promise.get_future();
1590     handler_->CallOn(pimpl_.get(), &Acl::impl::DisconnectLeConnections,
1591                      std::move(disconnect_promise));
1592     disconnect_future.wait();
1593     log::warn("Disconnected open ACL connections");
1594   }
1595 }
1596 
Shutdown()1597 void shim::Acl::Shutdown() {
1598   if (CheckForOrphanedAclConnections()) {
1599     std::promise<void> shutdown_promise;
1600     auto shutdown_future = shutdown_promise.get_future();
1601     handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownClassicConnections,
1602                      std::move(shutdown_promise));
1603     shutdown_future.wait();
1604 
1605     shutdown_promise = std::promise<void>();
1606 
1607     shutdown_future = shutdown_promise.get_future();
1608     handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownLeConnections, std::move(shutdown_promise));
1609     shutdown_future.wait();
1610     log::warn("Flushed open ACL connections");
1611   } else {
1612     log::info("All ACL connections have been previously closed");
1613   }
1614 }
1615 
FinalShutdown()1616 void shim::Acl::FinalShutdown() {
1617   std::promise<void> promise;
1618   auto future = promise.get_future();
1619   GetAclManager()->UnregisterCallbacks(this, std::move(promise));
1620   future.wait();
1621   log::debug("Unregistered classic callbacks from gd acl manager");
1622 
1623   promise = std::promise<void>();
1624   future = promise.get_future();
1625   GetAclManager()->UnregisterLeCallbacks(this, std::move(promise));
1626   future.wait();
1627   log::debug("Unregistered le callbacks from gd acl manager");
1628 
1629   promise = std::promise<void>();
1630   future = promise.get_future();
1631   handler_->CallOn(pimpl_.get(), &Acl::impl::FinalShutdown, std::move(promise));
1632   future.wait();
1633   log::info("Unregistered and cleared any orphaned ACL connections");
1634 }
1635 
ClearFilterAcceptList()1636 void shim::Acl::ClearFilterAcceptList() {
1637   handler_->CallOn(pimpl_.get(), &Acl::impl::clear_acceptlist);
1638 }
1639 
AddToAddressResolution(const hci::AddressWithType & address_with_type,const std::array<uint8_t,16> & peer_irk,const std::array<uint8_t,16> & local_irk)1640 void shim::Acl::AddToAddressResolution(const hci::AddressWithType& address_with_type,
1641                                        const std::array<uint8_t, 16>& peer_irk,
1642                                        const std::array<uint8_t, 16>& local_irk) {
1643   handler_->CallOn(pimpl_.get(), &Acl::impl::AddToAddressResolution, address_with_type, peer_irk,
1644                    local_irk);
1645 }
1646 
RemoveFromAddressResolution(const hci::AddressWithType & address_with_type)1647 void shim::Acl::RemoveFromAddressResolution(const hci::AddressWithType& address_with_type) {
1648   handler_->CallOn(pimpl_.get(), &Acl::impl::RemoveFromAddressResolution, address_with_type);
1649 }
1650 
ClearAddressResolution()1651 void shim::Acl::ClearAddressResolution() {
1652   handler_->CallOn(pimpl_.get(), &Acl::impl::ClearResolvingList);
1653 }
1654 
SetSystemSuspendState(bool suspended)1655 void shim::Acl::SetSystemSuspendState(bool suspended) {
1656   if (com::android::bluetooth::flags::adapter_suspend_mgmt()) {
1657     pimpl_->system_suspend_ = suspended;
1658     if (!suspended) {
1659       pimpl_->wakeup_wakelock_.release();
1660     }
1661   }
1662   handler_->CallOn(pimpl_.get(), &Acl::impl::SetSystemSuspendState, suspended);
1663 }
1664