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