• 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 "l2cap/le/internal/link.h"
18 
19 #include <chrono>
20 #include <memory>
21 
22 #include "hci/acl_manager/le_acl_connection.h"
23 #include "l2cap/internal/dynamic_channel_impl.h"
24 #include "l2cap/internal/parameter_provider.h"
25 #include "l2cap/le/dynamic_channel_manager.h"
26 #include "l2cap/le/internal/fixed_channel_impl.h"
27 #include "l2cap/le/internal/link_manager.h"
28 #include "os/alarm.h"
29 
30 namespace bluetooth {
31 namespace l2cap {
32 namespace le {
33 namespace internal {
34 
35 static constexpr uint16_t kDefaultMinimumCeLength = 0x0002;
36 static constexpr uint16_t kDefaultMaximumCeLength = 0x0C00;
37 
Link(os::Handler * l2cap_handler,std::unique_ptr<hci::acl_manager::LeAclConnection> acl_connection,l2cap::internal::ParameterProvider * parameter_provider,DynamicChannelServiceManagerImpl * dynamic_service_manager,FixedChannelServiceManagerImpl * fixed_service_manager,LinkManager * link_manager)38 Link::Link(os::Handler* l2cap_handler, std::unique_ptr<hci::acl_manager::LeAclConnection> acl_connection,
39            l2cap::internal::ParameterProvider* parameter_provider,
40            DynamicChannelServiceManagerImpl* dynamic_service_manager,
41            FixedChannelServiceManagerImpl* fixed_service_manager, LinkManager* link_manager)
42     : l2cap_handler_(l2cap_handler), acl_connection_(std::move(acl_connection)),
43       data_pipeline_manager_(l2cap_handler, this, acl_connection_->GetAclQueueEnd()),
44       parameter_provider_(parameter_provider), dynamic_service_manager_(dynamic_service_manager),
45       signalling_manager_(l2cap_handler_, this, &data_pipeline_manager_, dynamic_service_manager_,
46                           &dynamic_channel_allocator_),
47       link_manager_(link_manager) {
48   ASSERT(l2cap_handler_ != nullptr);
49   ASSERT(acl_connection_ != nullptr);
50   ASSERT(parameter_provider_ != nullptr);
51   link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
52                                        parameter_provider_->GetLeLinkIdleDisconnectTimeout());
53   acl_connection_->RegisterCallbacks(this, l2cap_handler_);
54 }
55 
OnAclDisconnected(hci::ErrorCode reason)56 void Link::OnAclDisconnected(hci::ErrorCode reason) {
57   fixed_channel_allocator_.OnAclDisconnected(static_cast<hci::ErrorCode>(reason));
58   dynamic_channel_allocator_.OnAclDisconnected(static_cast<hci::ErrorCode>(reason));
59 }
60 
OnDisconnection(hci::ErrorCode status)61 void Link::OnDisconnection(hci::ErrorCode status) {
62   OnAclDisconnected(status);
63 
64   link_manager_->OnDisconnect(GetAclConnection()->GetRemoteAddress());
65 }
66 
OnConnectionUpdate(hci::ErrorCode hci_status,uint16_t connection_interval,uint16_t connection_latency,uint16_t supervision_timeout)67 void Link::OnConnectionUpdate(
68     hci::ErrorCode hci_status,
69     uint16_t connection_interval,
70     uint16_t connection_latency,
71     uint16_t supervision_timeout) {
72   LOG_INFO(
73       "interval %hx latency %hx supervision_timeout %hx", connection_interval, connection_latency, supervision_timeout);
74   if (update_request_signal_id_ != kInvalidSignalId) {
75     hci::ErrorCode result = hci::ErrorCode::SUCCESS;
76     if (connection_interval > update_request_interval_max_ || connection_interval < update_request_interval_min_ ||
77         connection_latency != update_request_latency_ || supervision_timeout != update_request_supervision_timeout_) {
78       LOG_INFO("Received connection update complete with different parameters that provided by the Host");
79     }
80 
81     if (!CheckConnectionParameters(connection_interval, connection_interval, connection_latency, supervision_timeout)) {
82       result = hci::ErrorCode::UNSPECIFIED_ERROR;
83     }
84 
85     on_connection_update_complete(update_request_signal_id_, result);
86     update_request_signal_id_ = kInvalidSignalId;
87   }
88 }
89 
OnDataLengthChange(uint16_t tx_octets,uint16_t tx_time,uint16_t rx_octets,uint16_t rx_time)90 void Link::OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time) {
91   LOG_INFO("tx_octets %hx tx_time %hx rx_octets %hx rx_time %hx", tx_octets, tx_time, rx_octets, rx_time);
92 }
93 
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)94 void Link::OnReadRemoteVersionInformationComplete(
95     hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) {
96   LOG_INFO("lmp_version:%hhu manufacturer_name:%hu sub_version:%hu", lmp_version, manufacturer_name, sub_version);
97   link_manager_->OnReadRemoteVersionInformationComplete(
98       hci_status, GetDevice(), lmp_version, manufacturer_name, sub_version);
99 }
100 
OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status,uint64_t features)101 void Link::OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status, uint64_t features) {}
102 
OnPhyUpdate(hci::ErrorCode hci_status,uint8_t tx_phy,uint8_t rx_phy)103 void Link::OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy) {}
104 
OnLocalAddressUpdate(hci::AddressWithType address_with_type)105 void Link::OnLocalAddressUpdate(hci::AddressWithType address_with_type) {
106   acl_connection_->UpdateLocalAddress(address_with_type);
107 }
108 
Disconnect()109 void Link::Disconnect() {
110   acl_connection_->Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
111 }
112 
UpdateConnectionParameterFromRemote(SignalId signal_id,uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout)113 void Link::UpdateConnectionParameterFromRemote(SignalId signal_id, uint16_t conn_interval_min,
114                                                uint16_t conn_interval_max, uint16_t conn_latency,
115                                                uint16_t supervision_timeout) {
116   acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout,
117                                       kDefaultMinimumCeLength, kDefaultMaximumCeLength);
118   update_request_signal_id_ = signal_id;
119   update_request_interval_min_ = conn_interval_min;
120   update_request_interval_max_ = conn_interval_max;
121   update_request_latency_ = conn_latency;
122   update_request_supervision_timeout_ = supervision_timeout;
123 }
124 
CheckConnectionParameters(uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout)125 bool Link::CheckConnectionParameters(
126     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) {
127   if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
128       conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
129       supervision_timeout > 0x0C80) {
130     LOG_ERROR("Invalid parameter");
131     return false;
132   }
133 
134   // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms
135   // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms
136   // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in
137   // milliseconds.
138   uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1;
139   if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) {
140     LOG_ERROR("Invalid parameter");
141     return false;
142   }
143 
144   return true;
145 }
146 
SendConnectionParameterUpdate(uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout,uint16_t min_ce_length,uint16_t max_ce_length)147 void Link::SendConnectionParameterUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
148                                          uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length) {
149   if (acl_connection_->GetRole() == hci::Role::PERIPHERAL) {
150     // TODO: If both LL central and peripheral support 4.1, use HCI command directly
151     signalling_manager_.SendConnectionParameterUpdateRequest(conn_interval_min, conn_interval_max, conn_latency,
152                                                              supervision_timeout);
153     return;
154   }
155   acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout,
156                                       min_ce_length, max_ce_length);
157   update_request_signal_id_ = kInvalidSignalId;
158 }
159 
AllocateFixedChannel(Cid cid,SecurityPolicy security_policy)160 std::shared_ptr<FixedChannelImpl> Link::AllocateFixedChannel(Cid cid, SecurityPolicy security_policy) {
161   auto channel = fixed_channel_allocator_.AllocateChannel(cid);
162   data_pipeline_manager_.AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC);
163   return channel;
164 }
165 
IsFixedChannelAllocated(Cid cid)166 bool Link::IsFixedChannelAllocated(Cid cid) {
167   return fixed_channel_allocator_.IsChannelAllocated(cid);
168 }
169 
ReserveDynamicChannel()170 Cid Link::ReserveDynamicChannel() {
171   return dynamic_channel_allocator_.ReserveChannel();
172 }
173 
SendConnectionRequest(Psm psm,PendingDynamicChannelConnection pending_dynamic_channel_connection)174 void Link::SendConnectionRequest(Psm psm, PendingDynamicChannelConnection pending_dynamic_channel_connection) {
175   if (dynamic_channel_allocator_.IsPsmUsed(psm)) {
176     LOG_INFO("Psm %d is already connected", psm);
177     return;
178   }
179   auto reserved_cid = ReserveDynamicChannel();
180   auto mtu = pending_dynamic_channel_connection.configuration_.mtu;
181   local_cid_to_pending_dynamic_channel_connection_map_[reserved_cid] = std::move(pending_dynamic_channel_connection);
182   signalling_manager_.SendConnectionRequest(psm, reserved_cid, mtu);
183 }
184 
SendDisconnectionRequest(Cid local_cid,Cid remote_cid)185 void Link::SendDisconnectionRequest(Cid local_cid, Cid remote_cid) {
186   auto channel = dynamic_channel_allocator_.FindChannelByCid(local_cid);
187   if (channel == nullptr || channel->GetRemoteCid() != remote_cid) {
188     LOG_ERROR("Invalid cid");
189   }
190   signalling_manager_.SendDisconnectRequest(local_cid, remote_cid);
191 }
192 
OnOutgoingConnectionRequestFail(Cid local_cid,LeCreditBasedConnectionResponseResult response_result)193 void Link::OnOutgoingConnectionRequestFail(Cid local_cid, LeCreditBasedConnectionResponseResult response_result) {
194   if (local_cid_to_pending_dynamic_channel_connection_map_.find(local_cid) !=
195       local_cid_to_pending_dynamic_channel_connection_map_.end()) {
196     // TODO(hsz): Currently we only notify the client when the remote didn't send connection response SUCCESS.
197     //  Should we notify the client when the link failed to establish?
198     DynamicChannelManager::ConnectionResult result{
199         .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR,
200         .hci_error = hci::ErrorCode::SUCCESS,
201         .l2cap_connection_response_result = response_result,
202     };
203     NotifyChannelFail(local_cid, result);
204   }
205   dynamic_channel_allocator_.FreeChannel(local_cid);
206 }
207 
AllocateDynamicChannel(Psm psm,Cid remote_cid)208 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateDynamicChannel(Psm psm, Cid remote_cid) {
209   auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid);
210   if (channel != nullptr) {
211     data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
212                                          l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED);
213     RefreshRefCount();
214     channel->local_initiated_ = false;
215   }
216   return channel;
217 }
218 
AllocateReservedDynamicChannel(Cid reserved_cid,Psm psm,Cid remote_cid)219 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm,
220                                                                                           Cid remote_cid) {
221   auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid);
222   if (channel != nullptr) {
223     data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
224                                          l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED);
225     RefreshRefCount();
226     channel->local_initiated_ = true;
227   }
228   return channel;
229 }
230 
FreeDynamicChannel(Cid cid)231 void Link::FreeDynamicChannel(Cid cid) {
232   if (dynamic_channel_allocator_.FindChannelByCid(cid) == nullptr) {
233     return;
234   }
235   data_pipeline_manager_.DetachChannel(cid);
236   dynamic_channel_allocator_.FreeChannel(cid);
237   RefreshRefCount();
238 }
239 
RefreshRefCount()240 void Link::RefreshRefCount() {
241   int ref_count = 0;
242   ref_count += fixed_channel_allocator_.GetRefCount();
243   ref_count += dynamic_channel_allocator_.NumberOfChannels();
244   ASSERT_LOG(ref_count >= 0, "ref_count %d is less than 0", ref_count);
245   if (ref_count > 0) {
246     link_idle_disconnect_alarm_.Cancel();
247   } else {
248     link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
249                                          parameter_provider_->GetLeLinkIdleDisconnectTimeout());
250   }
251 }
252 
NotifyChannelCreation(Cid cid,std::unique_ptr<DynamicChannel> user_channel)253 void Link::NotifyChannelCreation(Cid cid, std::unique_ptr<DynamicChannel> user_channel) {
254   ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
255          local_cid_to_pending_dynamic_channel_connection_map_.end());
256   auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
257   pending_dynamic_channel_connection.handler_->Post(
258       common::BindOnce(std::move(pending_dynamic_channel_connection.on_open_callback_), std::move(user_channel)));
259   local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
260 }
261 
NotifyChannelFail(Cid cid,DynamicChannelManager::ConnectionResult result)262 void Link::NotifyChannelFail(Cid cid, DynamicChannelManager::ConnectionResult result) {
263   ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
264          local_cid_to_pending_dynamic_channel_connection_map_.end());
265   auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
266   // TODO(cmanton) Pass proper connection falure result to user
267   pending_dynamic_channel_connection.handler_->Post(
268       common::BindOnce(std::move(pending_dynamic_channel_connection.on_fail_callback_), result));
269   local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
270 }
271 
GetMps() const272 uint16_t Link::GetMps() const {
273   return parameter_provider_->GetLeMps();
274 }
275 
GetInitialCredit() const276 uint16_t Link::GetInitialCredit() const {
277   return parameter_provider_->GetLeInitialCredit();
278 }
279 
SendLeCredit(Cid local_cid,uint16_t credit)280 void Link::SendLeCredit(Cid local_cid, uint16_t credit) {
281   signalling_manager_.SendCredit(local_cid, credit);
282 }
283 
ReadRemoteVersionInformation()284 void Link::ReadRemoteVersionInformation() {
285   acl_connection_->ReadRemoteVersionInformation();
286 }
287 
on_connection_update_complete(SignalId signal_id,hci::ErrorCode error_code)288 void Link::on_connection_update_complete(SignalId signal_id, hci::ErrorCode error_code) {
289   if (!signal_id.IsValid()) {
290     LOG_INFO("Invalid signal_id");
291     return;
292   }
293   ConnectionParameterUpdateResponseResult result = (error_code == hci::ErrorCode::SUCCESS)
294                                                        ? ConnectionParameterUpdateResponseResult::ACCEPTED
295                                                        : ConnectionParameterUpdateResponseResult::REJECTED;
296   signalling_manager_.SendConnectionParameterUpdateResponse(SignalId(), result);
297 }
298 
OnPendingPacketChange(Cid local_cid,bool has_packet)299 void Link::OnPendingPacketChange(Cid local_cid, bool has_packet) {
300   if (has_packet) {
301     remaining_packets_to_be_sent_++;
302   } else {
303     remaining_packets_to_be_sent_--;
304   }
305   link_manager_->OnPendingPacketChange(GetDevice(), remaining_packets_to_be_sent_);
306 }
307 
308 }  // namespace internal
309 }  // namespace le
310 }  // namespace l2cap
311 }  // namespace bluetooth
312