• 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 
OnPhyUpdate(hci::ErrorCode hci_status,uint8_t tx_phy,uint8_t rx_phy)101 void Link::OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy) {}
102 
OnLocalAddressUpdate(hci::AddressWithType address_with_type)103 void Link::OnLocalAddressUpdate(hci::AddressWithType address_with_type) {
104   acl_connection_->UpdateLocalAddress(address_with_type);
105 }
106 
Disconnect()107 void Link::Disconnect() {
108   acl_connection_->Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
109 }
110 
UpdateConnectionParameterFromRemote(SignalId signal_id,uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout)111 void Link::UpdateConnectionParameterFromRemote(SignalId signal_id, uint16_t conn_interval_min,
112                                                uint16_t conn_interval_max, uint16_t conn_latency,
113                                                uint16_t supervision_timeout) {
114   acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout,
115                                       kDefaultMinimumCeLength, kDefaultMaximumCeLength);
116   update_request_signal_id_ = signal_id;
117   update_request_interval_min_ = conn_interval_min;
118   update_request_interval_max_ = conn_interval_max;
119   update_request_latency_ = conn_latency;
120   update_request_supervision_timeout_ = supervision_timeout;
121 }
122 
CheckConnectionParameters(uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout)123 bool Link::CheckConnectionParameters(
124     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) {
125   if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
126       conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
127       supervision_timeout > 0x0C80) {
128     LOG_ERROR("Invalid parameter");
129     return false;
130   }
131 
132   // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms
133   // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms
134   // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in
135   // milliseconds.
136   uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1;
137   if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) {
138     LOG_ERROR("Invalid parameter");
139     return false;
140   }
141 
142   return true;
143 }
144 
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)145 void Link::SendConnectionParameterUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
146                                          uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length) {
147   if (acl_connection_->GetRole() == hci::Role::PERIPHERAL) {
148     // TODO: If both LL central and peripheral support 4.1, use HCI command directly
149     signalling_manager_.SendConnectionParameterUpdateRequest(conn_interval_min, conn_interval_max, conn_latency,
150                                                              supervision_timeout);
151     return;
152   }
153   acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout,
154                                       min_ce_length, max_ce_length);
155   update_request_signal_id_ = kInvalidSignalId;
156 }
157 
AllocateFixedChannel(Cid cid,SecurityPolicy security_policy)158 std::shared_ptr<FixedChannelImpl> Link::AllocateFixedChannel(Cid cid, SecurityPolicy security_policy) {
159   auto channel = fixed_channel_allocator_.AllocateChannel(cid);
160   data_pipeline_manager_.AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC);
161   return channel;
162 }
163 
IsFixedChannelAllocated(Cid cid)164 bool Link::IsFixedChannelAllocated(Cid cid) {
165   return fixed_channel_allocator_.IsChannelAllocated(cid);
166 }
167 
ReserveDynamicChannel()168 Cid Link::ReserveDynamicChannel() {
169   return dynamic_channel_allocator_.ReserveChannel();
170 }
171 
SendConnectionRequest(Psm psm,PendingDynamicChannelConnection pending_dynamic_channel_connection)172 void Link::SendConnectionRequest(Psm psm, PendingDynamicChannelConnection pending_dynamic_channel_connection) {
173   if (dynamic_channel_allocator_.IsPsmUsed(psm)) {
174     LOG_INFO("Psm %d is already connected", psm);
175     return;
176   }
177   auto reserved_cid = ReserveDynamicChannel();
178   auto mtu = pending_dynamic_channel_connection.configuration_.mtu;
179   local_cid_to_pending_dynamic_channel_connection_map_[reserved_cid] = std::move(pending_dynamic_channel_connection);
180   signalling_manager_.SendConnectionRequest(psm, reserved_cid, mtu);
181 }
182 
SendDisconnectionRequest(Cid local_cid,Cid remote_cid)183 void Link::SendDisconnectionRequest(Cid local_cid, Cid remote_cid) {
184   auto channel = dynamic_channel_allocator_.FindChannelByCid(local_cid);
185   if (channel == nullptr || channel->GetRemoteCid() != remote_cid) {
186     LOG_ERROR("Invalid cid");
187   }
188   signalling_manager_.SendDisconnectRequest(local_cid, remote_cid);
189 }
190 
OnOutgoingConnectionRequestFail(Cid local_cid,LeCreditBasedConnectionResponseResult response_result)191 void Link::OnOutgoingConnectionRequestFail(Cid local_cid, LeCreditBasedConnectionResponseResult response_result) {
192   if (local_cid_to_pending_dynamic_channel_connection_map_.find(local_cid) !=
193       local_cid_to_pending_dynamic_channel_connection_map_.end()) {
194     // TODO(hsz): Currently we only notify the client when the remote didn't send connection response SUCCESS.
195     //  Should we notify the client when the link failed to establish?
196     DynamicChannelManager::ConnectionResult result{
197         .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR,
198         .hci_error = hci::ErrorCode::SUCCESS,
199         .l2cap_connection_response_result = response_result,
200     };
201     NotifyChannelFail(local_cid, result);
202   }
203   dynamic_channel_allocator_.FreeChannel(local_cid);
204 }
205 
AllocateDynamicChannel(Psm psm,Cid remote_cid)206 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateDynamicChannel(Psm psm, Cid remote_cid) {
207   auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid);
208   if (channel != nullptr) {
209     data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
210                                          l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED);
211     RefreshRefCount();
212     channel->local_initiated_ = false;
213   }
214   return channel;
215 }
216 
AllocateReservedDynamicChannel(Cid reserved_cid,Psm psm,Cid remote_cid)217 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm,
218                                                                                           Cid remote_cid) {
219   auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid);
220   if (channel != nullptr) {
221     data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
222                                          l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED);
223     RefreshRefCount();
224     channel->local_initiated_ = true;
225   }
226   return channel;
227 }
228 
FreeDynamicChannel(Cid cid)229 void Link::FreeDynamicChannel(Cid cid) {
230   if (dynamic_channel_allocator_.FindChannelByCid(cid) == nullptr) {
231     return;
232   }
233   data_pipeline_manager_.DetachChannel(cid);
234   dynamic_channel_allocator_.FreeChannel(cid);
235   RefreshRefCount();
236 }
237 
RefreshRefCount()238 void Link::RefreshRefCount() {
239   int ref_count = 0;
240   ref_count += fixed_channel_allocator_.GetRefCount();
241   ref_count += dynamic_channel_allocator_.NumberOfChannels();
242   ASSERT_LOG(ref_count >= 0, "ref_count %d is less than 0", ref_count);
243   if (ref_count > 0) {
244     link_idle_disconnect_alarm_.Cancel();
245   } else {
246     link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
247                                          parameter_provider_->GetLeLinkIdleDisconnectTimeout());
248   }
249 }
250 
NotifyChannelCreation(Cid cid,std::unique_ptr<DynamicChannel> user_channel)251 void Link::NotifyChannelCreation(Cid cid, std::unique_ptr<DynamicChannel> user_channel) {
252   ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
253          local_cid_to_pending_dynamic_channel_connection_map_.end());
254   auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
255   pending_dynamic_channel_connection.handler_->Post(
256       common::BindOnce(std::move(pending_dynamic_channel_connection.on_open_callback_), std::move(user_channel)));
257   local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
258 }
259 
NotifyChannelFail(Cid cid,DynamicChannelManager::ConnectionResult result)260 void Link::NotifyChannelFail(Cid cid, DynamicChannelManager::ConnectionResult result) {
261   ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
262          local_cid_to_pending_dynamic_channel_connection_map_.end());
263   auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
264   // TODO(cmanton) Pass proper connection falure result to user
265   pending_dynamic_channel_connection.handler_->Post(
266       common::BindOnce(std::move(pending_dynamic_channel_connection.on_fail_callback_), result));
267   local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
268 }
269 
GetMps() const270 uint16_t Link::GetMps() const {
271   return parameter_provider_->GetLeMps();
272 }
273 
GetInitialCredit() const274 uint16_t Link::GetInitialCredit() const {
275   return parameter_provider_->GetLeInitialCredit();
276 }
277 
SendLeCredit(Cid local_cid,uint16_t credit)278 void Link::SendLeCredit(Cid local_cid, uint16_t credit) {
279   signalling_manager_.SendCredit(local_cid, credit);
280 }
281 
ReadRemoteVersionInformation()282 void Link::ReadRemoteVersionInformation() {
283   acl_connection_->ReadRemoteVersionInformation();
284 }
285 
on_connection_update_complete(SignalId signal_id,hci::ErrorCode error_code)286 void Link::on_connection_update_complete(SignalId signal_id, hci::ErrorCode error_code) {
287   if (!signal_id.IsValid()) {
288     LOG_INFO("Invalid signal_id");
289     return;
290   }
291   ConnectionParameterUpdateResponseResult result = (error_code == hci::ErrorCode::SUCCESS)
292                                                        ? ConnectionParameterUpdateResponseResult::ACCEPTED
293                                                        : ConnectionParameterUpdateResponseResult::REJECTED;
294   signalling_manager_.SendConnectionParameterUpdateResponse(SignalId(), result);
295 }
296 
OnPendingPacketChange(Cid local_cid,bool has_packet)297 void Link::OnPendingPacketChange(Cid local_cid, bool has_packet) {
298   if (has_packet) {
299     remaining_packets_to_be_sent_++;
300   } else {
301     remaining_packets_to_be_sent_--;
302   }
303   link_manager_->OnPendingPacketChange(GetDevice(), remaining_packets_to_be_sent_);
304 }
305 
306 }  // namespace internal
307 }  // namespace le
308 }  // namespace l2cap
309 }  // namespace bluetooth
310