1 /******************************************************************************
2 *
3 * Copyright 2009-2012 Broadcom Corporation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 /******************************************************************************
20 *
21 * this file contains functions relating to BLE management.
22 *
23 ******************************************************************************/
24
25 #define LOG_TAG "l2c_ble"
26
27 #include <base/strings/stringprintf.h>
28 #include <bluetooth/log.h>
29 #include <com_android_bluetooth_flags.h>
30
31 #ifdef __ANDROID__
32 #include <android/sysprop/BluetoothProperties.sysprop.h>
33 #endif
34
35 #include "btif/include/core_callbacks.h"
36 #include "btif/include/stack_manager_t.h"
37 #include "hci/controller_interface.h"
38 #include "hci/hci_interface.h"
39 #include "internal_include/bt_target.h"
40 #include "main/shim/entry.h"
41 #include "osi/include/allocator.h"
42 #include "osi/include/properties.h"
43 #include "stack/btm/btm_ble_sec.h"
44 #include "stack/btm/btm_int_types.h"
45 #include "stack/btm/btm_sec.h"
46 #include "stack/btm/btm_sec_int_types.h"
47 #include "stack/connection_manager/connection_manager.h"
48 #include "stack/include/acl_api.h"
49 #include "stack/include/bt_psm_types.h"
50 #include "stack/include/bt_types.h"
51 #include "stack/include/btm_ble_api_types.h"
52 #include "stack/include/btm_client_interface.h"
53 #include "stack/include/btm_log_history.h"
54 #include "stack/include/btm_status.h"
55 #include "stack/include/l2cap_acl_interface.h"
56 #include "stack/include/l2cap_controller_interface.h"
57 #include "stack/include/l2cap_hci_link_interface.h"
58 #include "stack/include/l2cap_interface.h"
59 #include "stack/include/l2cdefs.h"
60 #include "stack/include/main_thread.h"
61 #include "stack/l2cap/l2c_int.h"
62 #include "types/raw_address.h"
63
64 using namespace bluetooth;
65
66 namespace {
67 constexpr char kBtmLogTag[] = "L2CAP";
68 }
69
70 extern tBTM_CB btm_cb;
71
72 void l2cble_start_conn_update(tL2C_LCB* p_lcb);
73
L2CA_Consolidate(const RawAddress & identity_addr,const RawAddress & rpa)74 void L2CA_Consolidate(const RawAddress& identity_addr, const RawAddress& rpa) {
75 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rpa, BT_TRANSPORT_LE);
76 if (p_lcb == nullptr) {
77 return;
78 }
79
80 log::info("consolidating l2c_lcb record {} -> {}", rpa, identity_addr);
81 p_lcb->remote_bd_addr = identity_addr;
82 }
83
L2CA_GetBleConnRole(const RawAddress & bd_addr)84 hci_role_t L2CA_GetBleConnRole(const RawAddress& bd_addr) {
85 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
86 if (p_lcb == nullptr) {
87 return HCI_ROLE_UNKNOWN;
88 }
89 return p_lcb->LinkRole();
90 }
91
92 /*******************************************************************************
93 *
94 * Function l2cble_notify_le_connection
95 *
96 * Description This function notify the l2cap connection to the app layer
97 *
98 * Returns none
99 *
100 ******************************************************************************/
l2cble_notify_le_connection(const RawAddress & bda)101 void l2cble_notify_le_connection(const RawAddress& bda) {
102 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
103 if (p_lcb == nullptr) {
104 log::warn("Received notification for le connection but no lcb found");
105 return;
106 }
107
108 if (get_btm_client_interface().peer.BTM_IsAclConnectionUp(bda, BT_TRANSPORT_LE) &&
109 p_lcb->link_state != LST_CONNECTED) {
110 /* update link status */
111 // TODO Move this back into acl layer
112 btm_establish_continue_from_address(bda, BT_TRANSPORT_LE);
113 /* update l2cap link status and send callback */
114 p_lcb->link_state = LST_CONNECTED;
115 l2cu_process_fixed_chnl_resp(p_lcb);
116 }
117
118 /* For all channels, send the event through their FSMs */
119 for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) {
120 if (p_ccb->chnl_state == CST_CLOSED) {
121 l2c_csm_execute(p_ccb, L2CEVT_LP_CONNECT_CFM, NULL);
122 }
123 }
124 }
125
126 /** This function is called when an HCI Connection Complete event is received.
127 */
l2cble_conn_comp(uint16_t handle,tHCI_ROLE role,const RawAddress & bda,tBLE_ADDR_TYPE,uint16_t conn_interval,uint16_t conn_latency,uint16_t conn_timeout)128 bool l2cble_conn_comp(uint16_t handle, tHCI_ROLE role, const RawAddress& bda,
129 tBLE_ADDR_TYPE /* type */, uint16_t conn_interval, uint16_t conn_latency,
130 uint16_t conn_timeout) {
131 // role == HCI_ROLE_CENTRAL => scanner completed connection
132 // role == HCI_ROLE_PERIPHERAL => advertiser completed connection
133
134 /* See if we have a link control block for the remote device */
135 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
136
137 /* If we do not have one, create one. this is auto connection complete. */
138 if (!p_lcb) {
139 p_lcb = l2cu_allocate_lcb(bda, false, BT_TRANSPORT_LE);
140 if (!p_lcb) {
141 log::error("Unable to allocate link resource for le acl connection");
142 return false;
143 } else {
144 if (!l2cu_initialize_fixed_ccb(p_lcb, L2CAP_ATT_CID)) {
145 log::error("Unable to allocate channel resource for le acl connection");
146 return false;
147 }
148 }
149 p_lcb->link_state = LST_CONNECTING;
150 } else if (role == HCI_ROLE_CENTRAL && p_lcb->link_state != LST_CONNECTING) {
151 log::error(
152 "Received le acl connection as role central but not in connecting "
153 "state");
154 return false;
155 }
156
157 if (role == HCI_ROLE_CENTRAL) {
158 alarm_cancel(p_lcb->l2c_lcb_timer);
159 }
160
161 /* Save the handle */
162 l2cu_set_lcb_handle(*p_lcb, handle);
163
164 /* Connected OK. Change state to connected, we were scanning so we are central
165 */
166 if (role == HCI_ROLE_CENTRAL) {
167 p_lcb->SetLinkRoleAsCentral();
168 } else {
169 p_lcb->SetLinkRoleAsPeripheral();
170 }
171
172 p_lcb->transport = BT_TRANSPORT_LE;
173
174 /* update link parameter, set peripheral link as non-spec default upon link up
175 */
176 p_lcb->min_interval = p_lcb->max_interval = conn_interval;
177 p_lcb->timeout = conn_timeout;
178 p_lcb->latency = conn_latency;
179 p_lcb->conn_update_mask = L2C_BLE_NOT_DEFAULT_PARAM;
180 p_lcb->conn_update_blocked_by_profile_connection = false;
181 p_lcb->conn_update_blocked_by_service_discovery = false;
182
183 p_lcb->subrate_req_mask = 0;
184 p_lcb->subrate_min = 1;
185 p_lcb->subrate_max = 1;
186 p_lcb->max_latency = 0;
187 p_lcb->cont_num = 0;
188 p_lcb->supervision_tout = 0;
189
190 p_lcb->peer_chnl_mask[0] =
191 L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT;
192
193 if (role == HCI_ROLE_PERIPHERAL) {
194 if (!bluetooth::shim::GetController()->SupportsBlePeripheralInitiatedFeaturesExchange()) {
195 p_lcb->link_state = LST_CONNECTED;
196 l2cu_process_fixed_chnl_resp(p_lcb);
197 }
198 }
199 return true;
200 }
201
202 /*******************************************************************************
203 *
204 * Function l2cble_handle_connect_rsp_neg
205 *
206 * Description This function sends error message to all the
207 * outstanding channels
208 *
209 * Returns void
210 *
211 ******************************************************************************/
l2cble_handle_connect_rsp_neg(tL2C_LCB * p_lcb,tL2C_CONN_INFO * con_info)212 static void l2cble_handle_connect_rsp_neg(tL2C_LCB* p_lcb, tL2C_CONN_INFO* con_info) {
213 tL2C_CCB* temp_p_ccb = NULL;
214 for (int i = 0; i < p_lcb->pending_ecoc_conn_cnt; i++) {
215 uint16_t cid = p_lcb->pending_ecoc_connection_cids[i];
216 temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
217 l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, con_info);
218 }
219
220 p_lcb->pending_ecoc_conn_cnt = 0;
221 memset(p_lcb->pending_ecoc_connection_cids, 0, L2CAP_CREDIT_BASED_MAX_CIDS);
222 }
223
224 /*******************************************************************************
225 *
226 * Function l2cble_process_sig_cmd
227 *
228 * Description This function is called when a signalling packet is received
229 * on the BLE signalling CID
230 *
231 * Returns void
232 *
233 ******************************************************************************/
l2cble_process_sig_cmd(tL2C_LCB * p_lcb,uint8_t * p,uint16_t pkt_len)234 void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) {
235 uint8_t* p_pkt_end;
236 uint8_t cmd_code, id;
237 uint16_t cmd_len;
238 uint16_t min_interval, max_interval, latency, timeout;
239 uint16_t lcid = 0, rcid = 0, mtu = 0, mps = 0, initial_credit = 0;
240 tL2C_CCB *p_ccb = NULL, *temp_p_ccb = NULL;
241 tL2C_RCB* p_rcb;
242 uint16_t credit;
243 uint8_t num_of_channels;
244
245 p_pkt_end = p + pkt_len;
246
247 if (p + 4 > p_pkt_end) {
248 log::error("invalid read");
249 return;
250 }
251
252 STREAM_TO_UINT8(cmd_code, p);
253 STREAM_TO_UINT8(id, p);
254 STREAM_TO_UINT16(cmd_len, p);
255
256 /* Check command length does not exceed packet length */
257 if ((p + cmd_len) > p_pkt_end) {
258 log::warn("L2CAP - LE - format error, pkt_len: {} cmd_len: {} code: {}", pkt_len, cmd_len,
259 cmd_code);
260 return;
261 }
262
263 switch (cmd_code) {
264 case L2CAP_CMD_REJECT: {
265 if (p + 2 > p_pkt_end) {
266 log::error(
267 "invalid L2CAP_CMD_REJECT packet, not containing enough data for "
268 "`reason` field");
269 return;
270 }
271
272 uint16_t reason{};
273 STREAM_TO_UINT16(reason, p);
274
275 if (reason == L2CAP_CMD_REJ_NOT_UNDERSTOOD && p_lcb->pending_ecoc_conn_cnt > 0) {
276 tL2C_CONN_INFO con_info = {
277 .bd_addr{},
278 .hci_status{},
279 .psm{},
280 .l2cap_result =
281 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_PSM),
282 .l2cap_status{},
283 .remote_cid{},
284 .lcids{},
285 .peer_mtu{},
286 };
287 l2cble_handle_connect_rsp_neg(p_lcb, &con_info);
288 }
289 } break;
290
291 case L2CAP_CMD_ECHO_REQ:
292 case L2CAP_CMD_ECHO_RSP:
293 case L2CAP_CMD_INFO_RSP:
294 case L2CAP_CMD_INFO_REQ:
295 l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
296 break;
297
298 case L2CAP_CMD_BLE_UPDATE_REQ:
299 if (p + 8 > p_pkt_end) {
300 log::error("invalid read");
301 return;
302 }
303
304 STREAM_TO_UINT16(min_interval, p); /* 0x0006 - 0x0C80 */
305 STREAM_TO_UINT16(max_interval, p); /* 0x0006 - 0x0C80 */
306 STREAM_TO_UINT16(latency, p); /* 0x0000 - 0x03E8 */
307 STREAM_TO_UINT16(timeout, p); /* 0x000A - 0x0C80 */
308 /* If we are a central, the peripheral wants to update the parameters */
309 if (p_lcb->IsLinkRoleCentral()) {
310 stack::l2cap::get_interface().L2CA_AdjustConnectionIntervals(
311 &min_interval, &max_interval,
312 osi_property_get_int32("bluetooth.core.le.min_connection_interval",
313 BTM_BLE_CONN_INT_MIN_LIMIT));
314
315 if (min_interval < BTM_BLE_CONN_INT_MIN || min_interval > BTM_BLE_CONN_INT_MAX ||
316 max_interval < BTM_BLE_CONN_INT_MIN || max_interval > BTM_BLE_CONN_INT_MAX ||
317 latency > BTM_BLE_CONN_LATENCY_MAX ||
318 /*(timeout >= max_interval && latency > (timeout * 10/(max_interval
319 * 1.25) - 1)) ||*/
320 timeout < BTM_BLE_CONN_SUP_TOUT_MIN || timeout > BTM_BLE_CONN_SUP_TOUT_MAX ||
321 max_interval < min_interval) {
322 l2cu_send_peer_ble_par_rsp(p_lcb, tL2CAP_CFG_RESULT::L2CAP_CFG_UNACCEPTABLE_PARAMS, id);
323 } else {
324 l2cu_send_peer_ble_par_rsp(p_lcb, tL2CAP_CFG_RESULT::L2CAP_CFG_OK, id);
325
326 p_lcb->min_interval = min_interval;
327 p_lcb->max_interval = max_interval;
328 p_lcb->latency = latency;
329 p_lcb->timeout = timeout;
330 p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
331
332 l2cble_start_conn_update(p_lcb);
333 }
334 } else {
335 l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
336 }
337 break;
338
339 case L2CAP_CMD_BLE_UPDATE_RSP:
340 p += 2;
341 break;
342
343 case L2CAP_CMD_CREDIT_BASED_CONN_REQ: {
344 if (p + 10 > p_pkt_end) {
345 log::error("invalid L2CAP_CMD_CREDIT_BASED_CONN_REQ len");
346 return;
347 }
348
349 tL2C_CONN_INFO con_info{};
350 STREAM_TO_UINT16(con_info.psm, p);
351 STREAM_TO_UINT16(mtu, p);
352 STREAM_TO_UINT16(mps, p);
353 STREAM_TO_UINT16(initial_credit, p);
354
355 /* Check how many channels remote side wants. */
356 num_of_channels = (p_pkt_end - p) / sizeof(uint16_t);
357 if (num_of_channels > L2CAP_CREDIT_BASED_MAX_CIDS) {
358 log::warn("L2CAP - invalid number of channels requested: {}", num_of_channels);
359 l2cu_reject_credit_based_conn_req(
360 p_lcb, id, L2CAP_CREDIT_BASED_MAX_CIDS,
361 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INVALID_PARAMETERS);
362 return;
363 }
364
365 log::debug(
366 "Recv L2CAP_CMD_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, "
367 "initial credit = {}num_of_channels = {}",
368 mtu, mps, initial_credit, num_of_channels);
369
370 /* Check PSM Support */
371 p_rcb = l2cu_find_ble_rcb_by_psm(con_info.psm);
372 if (p_rcb == NULL) {
373 log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}", con_info.psm);
374 l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels,
375 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_PSM);
376 return;
377 }
378
379 if (p_lcb->pending_ecoc_conn_cnt > 0) {
380 log::warn("L2CAP - L2CAP_CMD_CREDIT_BASED_CONN_REQ collision:");
381 if (p_rcb->api.pL2CA_CreditBasedCollisionInd_Cb && con_info.psm == BT_PSM_EATT) {
382 (*p_rcb->api.pL2CA_CreditBasedCollisionInd_Cb)(p_lcb->remote_bd_addr);
383 }
384 l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels,
385 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES);
386 return;
387 }
388
389 p_lcb->pending_ecoc_conn_cnt = num_of_channels;
390
391 if (!p_rcb->api.pL2CA_CreditBasedConnectInd_Cb) {
392 log::warn("L2CAP - rcvd conn req for outgoing-only connection PSM: {}", con_info.psm);
393 l2cu_reject_credit_based_conn_req(p_lcb, id, num_of_channels,
394 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_PSM);
395 return;
396 }
397
398 /* validate the parameters */
399 if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || mps < L2CAP_CREDIT_BASED_MIN_MPS ||
400 mps > L2CAP_LE_MAX_MPS) {
401 log::error("L2CAP don't like the params");
402 l2cu_reject_credit_based_conn_req(
403 p_lcb, id, num_of_channels,
404 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INVALID_PARAMETERS);
405 return;
406 }
407
408 bool lead_cid_set = false;
409
410 for (int i = 0; i < num_of_channels; i++) {
411 STREAM_TO_UINT16(rcid, p);
412 temp_p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
413 if (temp_p_ccb) {
414 log::warn("L2CAP - rcvd conn req for duplicated cid: 0x{:04x}", rcid);
415 p_lcb->pending_ecoc_connection_cids[i] = 0;
416 p_lcb->pending_l2cap_result = static_cast<tL2CAP_CONN>(
417 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
418 } else {
419 /* Allocate a ccb for this.*/
420 temp_p_ccb = l2cu_allocate_ccb(p_lcb, 0, con_info.psm == BT_PSM_EATT /* is_eatt */);
421 if (temp_p_ccb == NULL) {
422 log::error("L2CAP - unable to allocate CCB");
423 p_lcb->pending_ecoc_connection_cids[i] = 0;
424 p_lcb->pending_l2cap_result =
425 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES);
426 continue;
427 }
428
429 temp_p_ccb->ecoc = true;
430 temp_p_ccb->remote_id = id;
431 temp_p_ccb->p_rcb = p_rcb;
432 temp_p_ccb->remote_cid = rcid;
433
434 temp_p_ccb->peer_conn_cfg.mtu = mtu;
435 temp_p_ccb->peer_conn_cfg.mps = mps;
436 temp_p_ccb->peer_conn_cfg.credits = initial_credit;
437
438 temp_p_ccb->tx_mps = mps;
439 temp_p_ccb->ble_sdu = NULL;
440 temp_p_ccb->ble_sdu_length = 0;
441 temp_p_ccb->is_first_seg = true;
442 temp_p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
443
444 /* This list will be used to prepare response */
445 p_lcb->pending_ecoc_connection_cids[i] = temp_p_ccb->local_cid;
446
447 /*This is going to be our lead p_ccb for state machine */
448 if (!lead_cid_set) {
449 p_ccb = temp_p_ccb;
450 p_ccb->local_conn_cfg.mtu = L2CAP_SDU_LENGTH_LE_MAX;
451 p_ccb->local_conn_cfg.mps =
452 bluetooth::shim::GetController()->GetLeBufferSize().le_data_packet_length_;
453 p_lcb->pending_lead_cid = p_ccb->local_cid;
454 lead_cid_set = true;
455 }
456 }
457 }
458
459 if (!lead_cid_set) {
460 log::error("L2CAP - unable to allocate CCB");
461 l2cu_reject_credit_based_conn_req(
462 p_lcb, id, num_of_channels,
463 static_cast<tL2CAP_LE_RESULT_CODE>(p_lcb->pending_l2cap_result));
464 return;
465 }
466
467 log::debug("L2CAP - processing peer credit based connect request");
468 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_REQ, NULL);
469 break;
470 }
471 case L2CAP_CMD_CREDIT_BASED_CONN_RES: {
472 if (p + 8 > p_pkt_end) {
473 log::error("invalid L2CAP_CMD_CREDIT_BASED_CONN_RES len");
474 return;
475 }
476
477 log::verbose("Recv L2CAP_CMD_CREDIT_BASED_CONN_RES");
478 /* For all channels, see whose identifier matches this id */
479 for (temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb;
480 temp_p_ccb = temp_p_ccb->p_next_ccb) {
481 if (temp_p_ccb->local_id == id) {
482 p_ccb = temp_p_ccb;
483 break;
484 }
485 }
486
487 if (!p_ccb) {
488 tL2C_CONN_INFO con_info{};
489 log::verbose("Cannot find matching connection req");
490 con_info.l2cap_result =
491 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INVALID_SOURCE_CID);
492 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
493 return;
494 }
495
496 tL2C_CONN_INFO con_info{};
497 STREAM_TO_UINT16(mtu, p);
498 STREAM_TO_UINT16(mps, p);
499 STREAM_TO_UINT16(initial_credit, p);
500 uint16_t result_u16;
501 STREAM_TO_UINT16(result_u16, p);
502 con_info.l2cap_result = static_cast<tL2CAP_CONN>(result_u16);
503
504 /* When one of these result is sent back that means,
505 * all the channels has been rejected
506 */
507 if (con_info.l2cap_result ==
508 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_PSM) ||
509 con_info.l2cap_result ==
510 static_cast<tL2CAP_CONN>(
511 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION) ||
512 con_info.l2cap_result ==
513 static_cast<tL2CAP_CONN>(
514 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP) ||
515 con_info.l2cap_result ==
516 static_cast<tL2CAP_CONN>(
517 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_AUTHORIZATION) ||
518 con_info.l2cap_result ==
519 static_cast<tL2CAP_CONN>(
520 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_UNACCEPTABLE_PARAMETERS) ||
521 con_info.l2cap_result ==
522 static_cast<tL2CAP_CONN>(
523 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INVALID_PARAMETERS)) {
524 log::error("L2CAP - not accepted. Status {}", con_info.l2cap_result);
525 l2cble_handle_connect_rsp_neg(p_lcb, &con_info);
526 return;
527 }
528
529 /* validate the parameters */
530 if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || mps < L2CAP_CREDIT_BASED_MIN_MPS ||
531 mps > L2CAP_LE_MAX_MPS) {
532 log::error("L2CAP - invalid params");
533 con_info.l2cap_result =
534 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INVALID_PARAMETERS);
535 l2cble_handle_connect_rsp_neg(p_lcb, &con_info);
536 return;
537 }
538
539 /* At least some of the channels has been created and parameters are
540 * good*/
541 num_of_channels = (p_pkt_end - p) / sizeof(uint16_t);
542 if (num_of_channels != p_lcb->pending_ecoc_conn_cnt) {
543 log::error(
544 "Incorrect response.expected num of channels = {} received num of "
545 "channels = {}",
546 num_of_channels, p_lcb->pending_ecoc_conn_cnt);
547 return;
548 }
549
550 log::verbose(
551 "mtu = {}, mps = {}, initial_credit = {}, con_info.l2cap_result = "
552 "{} num_of_channels = {}",
553 mtu, mps, initial_credit, con_info.l2cap_result, num_of_channels);
554
555 con_info.peer_mtu = mtu;
556
557 /* Copy request data and clear it so user can perform another connect if
558 * needed in the callback. */
559 p_lcb->pending_ecoc_conn_cnt = 0;
560 uint16_t cids[L2CAP_CREDIT_BASED_MAX_CIDS];
561 std::copy_n(p_lcb->pending_ecoc_connection_cids, L2CAP_CREDIT_BASED_MAX_CIDS, cids);
562 std::fill_n(p_lcb->pending_ecoc_connection_cids, L2CAP_CREDIT_BASED_MAX_CIDS, 0);
563
564 for (int i = 0; i < num_of_channels; i++) {
565 uint16_t cid = cids[i];
566 STREAM_TO_UINT16(rcid, p);
567
568 if (rcid != 0) {
569 /* If remote cid is duplicated then disconnect original channel
570 * and current channel by sending event to upper layer
571 */
572 temp_p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
573 if (temp_p_ccb != nullptr) {
574 log::error(
575 "Already Allocated Destination cid. rcid = {} send "
576 "peer_disc_req",
577 rcid);
578
579 l2cu_send_peer_disc_req(temp_p_ccb);
580
581 temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
582 con_info.l2cap_result = static_cast<tL2CAP_CONN>(
583 tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_UNACCEPTABLE_PARAMETERS);
584 l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, &con_info);
585 continue;
586 }
587 }
588
589 temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
590 temp_p_ccb->remote_cid = rcid;
591
592 log::verbose("local cid = {} remote cid = {}", cid, temp_p_ccb->remote_cid);
593
594 /* Check if peer accepted channel, if not release the one not
595 * created
596 */
597 if (temp_p_ccb->remote_cid == 0) {
598 l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG, &con_info);
599 } else {
600 temp_p_ccb->tx_mps = mps;
601 temp_p_ccb->ble_sdu = NULL;
602 temp_p_ccb->ble_sdu_length = 0;
603 temp_p_ccb->is_first_seg = true;
604 temp_p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
605 temp_p_ccb->peer_conn_cfg.mtu = mtu;
606 temp_p_ccb->peer_conn_cfg.mps = mps;
607 temp_p_ccb->peer_conn_cfg.credits = initial_credit;
608
609 l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP, &con_info);
610 }
611 }
612 } break;
613 case L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ: {
614 if (p + 6 > p_pkt_end) {
615 l2cu_send_ble_reconfig_rsp(p_lcb, id,
616 tL2CAP_RECONFIG_RESULT::L2CAP_RECONFIG_UNACCAPTED_PARAM);
617 return;
618 }
619
620 STREAM_TO_UINT16(mtu, p);
621 STREAM_TO_UINT16(mps, p);
622
623 /* validate the parameters */
624 if (mtu < L2CAP_CREDIT_BASED_MIN_MTU || mps < L2CAP_CREDIT_BASED_MIN_MPS ||
625 mps > L2CAP_LE_MAX_MPS) {
626 log::error("L2CAP - invalid params");
627 l2cu_send_ble_reconfig_rsp(p_lcb, id,
628 tL2CAP_RECONFIG_RESULT::L2CAP_RECONFIG_UNACCAPTED_PARAM);
629 return;
630 }
631
632 /* Check how many channels remote side wants to reconfigure */
633 num_of_channels = (p_pkt_end - p) / sizeof(uint16_t);
634
635 log::verbose(
636 "Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_REQ with mtu = {}, mps = {}, "
637 "num_of_channels = {}",
638 mtu, mps, num_of_channels);
639
640 uint8_t* p_tmp = p;
641 for (int i = 0; i < num_of_channels; i++) {
642 STREAM_TO_UINT16(rcid, p_tmp);
643 p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
644 if (!p_ccb) {
645 log::warn("L2CAP - rcvd config req for non existing cid: 0x{:04x}", rcid);
646 l2cu_send_ble_reconfig_rsp(p_lcb, id,
647 tL2CAP_RECONFIG_RESULT::L2CAP_RECONFIG_INVALID_DCID);
648 return;
649 }
650
651 if (p_ccb->peer_conn_cfg.mtu > mtu) {
652 log::warn("L2CAP - rcvd config req mtu reduction new mtu < mtu ({} < {})", mtu,
653 p_ccb->peer_conn_cfg.mtu);
654 l2cu_send_ble_reconfig_rsp(
655 p_lcb, id, tL2CAP_RECONFIG_RESULT::L2CAP_RECONFIG_REDUCTION_MTU_NO_ALLOWED);
656 return;
657 }
658
659 if (p_ccb->peer_conn_cfg.mps > mps && num_of_channels > 1) {
660 log::warn("L2CAP - rcvd config req mps reduction new mps < mps ({} < {})", mtu,
661 p_ccb->peer_conn_cfg.mtu);
662 l2cu_send_ble_reconfig_rsp(
663 p_lcb, id, tL2CAP_RECONFIG_RESULT::L2CAP_RECONFIG_REDUCTION_MPS_NO_ALLOWED);
664 return;
665 }
666 }
667
668 for (int i = 0; i < num_of_channels; i++) {
669 STREAM_TO_UINT16(rcid, p);
670
671 /* Store new values */
672 p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
673 p_ccb->peer_conn_cfg.mtu = mtu;
674 p_ccb->peer_conn_cfg.mps = mps;
675 p_ccb->tx_mps = mps;
676
677 tL2CAP_LE_CFG_INFO le_cfg;
678 le_cfg.mps = mps;
679 le_cfg.mtu = mtu;
680
681 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_REQ, &le_cfg);
682 }
683
684 l2cu_send_ble_reconfig_rsp(p_lcb, id, tL2CAP_RECONFIG_RESULT::L2CAP_RECONFIG_SUCCEED);
685
686 break;
687 }
688
689 case L2CAP_CMD_CREDIT_BASED_RECONFIG_RES: {
690 uint16_t result_u16;
691 if (p + sizeof(tL2CAP_CFG_RESULT) > p_pkt_end) {
692 log::error("invalid read");
693 return;
694 }
695 STREAM_TO_UINT16(result_u16, p);
696 tL2CAP_CFG_RESULT result = static_cast<tL2CAP_CFG_RESULT>(result_u16);
697
698 log::verbose("Recv L2CAP_CMD_CREDIT_BASED_RECONFIG_RES for result:{}",
699 l2cap_cfg_result_text(result));
700
701 p_lcb->pending_ecoc_reconfig_cfg.result = result;
702
703 /* All channels which are in reconfiguration state are marked with
704 * reconfig_started flag. Find it and send response
705 */
706 for (temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb;
707 temp_p_ccb = temp_p_ccb->p_next_ccb) {
708 if ((temp_p_ccb->in_use) && (temp_p_ccb->reconfig_started)) {
709 l2c_csm_execute(temp_p_ccb, L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_RSP,
710 &p_lcb->pending_ecoc_reconfig_cfg);
711
712 temp_p_ccb->reconfig_started = false;
713 if (result == tL2CAP_CFG_RESULT::L2CAP_CFG_OK) {
714 temp_p_ccb->local_conn_cfg = p_lcb->pending_ecoc_reconfig_cfg;
715 }
716 }
717 }
718
719 break;
720 }
721
722 case L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ: {
723 tL2C_CONN_INFO con_info{};
724 if (p + 10 > p_pkt_end) {
725 log::error("invalid read");
726 return;
727 }
728
729 STREAM_TO_UINT16(con_info.psm, p);
730 STREAM_TO_UINT16(rcid, p);
731 STREAM_TO_UINT16(mtu, p);
732 STREAM_TO_UINT16(mps, p);
733 STREAM_TO_UINT16(initial_credit, p);
734
735 log::verbose(
736 "Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ with mtu = {}, mps = {}, "
737 "initial credit = {}",
738 mtu, mps, initial_credit);
739
740 p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, rcid);
741 if (p_ccb) {
742 log::warn("L2CAP - rcvd conn req for duplicated cid: 0x{:04x}", rcid);
743 l2cu_reject_ble_coc_connection(
744 p_lcb, id, tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
745 break;
746 }
747
748 p_rcb = l2cu_find_ble_rcb_by_psm(con_info.psm);
749 if (p_rcb == NULL) {
750 log::warn("L2CAP - rcvd conn req for unknown PSM: 0x{:04x}", con_info.psm);
751 l2cu_reject_ble_coc_connection(p_lcb, id, tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_PSM);
752 break;
753 } else {
754 if (!p_rcb->api.pL2CA_ConnectInd_Cb) {
755 log::warn("L2CAP - rcvd conn req for outgoing-only connection PSM: {}", con_info.psm);
756 l2cu_reject_ble_coc_connection(p_lcb, id, tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_PSM);
757 break;
758 }
759 }
760
761 /* Allocate a ccb for this.*/
762 p_ccb = l2cu_allocate_ccb(p_lcb, 0, con_info.psm == BT_PSM_EATT /* is_eatt */);
763 if (p_ccb == NULL) {
764 log::error("L2CAP - unable to allocate CCB");
765 l2cu_reject_ble_connection(p_ccb, id, tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES);
766 break;
767 }
768
769 /* validate the parameters */
770 if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MPS || mps > L2CAP_LE_MAX_MPS) {
771 log::error("L2CAP do not like the params");
772 l2cu_reject_ble_connection(p_ccb, id, tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES);
773 break;
774 }
775
776 p_ccb->remote_id = id;
777 p_ccb->p_rcb = p_rcb;
778 p_ccb->remote_cid = rcid;
779
780 if (com::android::bluetooth::flags::socket_settings_api()) { // Added with aosp/3349377
781 p_ccb->local_conn_cfg.mtu = p_rcb->coc_cfg.mtu;
782 p_ccb->local_conn_cfg.mps = p_rcb->coc_cfg.mps;
783 } else {
784 p_ccb->local_conn_cfg.mtu = L2CAP_SDU_LENGTH_LE_MAX;
785 p_ccb->local_conn_cfg.mps =
786 bluetooth::shim::GetController()->GetLeBufferSize().le_data_packet_length_;
787 }
788 if (com::android::bluetooth::flags::socket_settings_api()) { // Added with aosp/3349376
789 p_ccb->local_conn_cfg.credits = p_rcb->coc_cfg.credits;
790 p_ccb->remote_credit_count = p_rcb->coc_cfg.credits;
791 } else {
792 p_ccb->local_conn_cfg.credits = L2CA_LeCreditDefault();
793 p_ccb->remote_credit_count = L2CA_LeCreditDefault();
794 }
795
796 p_ccb->peer_conn_cfg.mtu = mtu;
797 p_ccb->peer_conn_cfg.mps = mps;
798 p_ccb->peer_conn_cfg.credits = initial_credit;
799
800 p_ccb->tx_mps = mps;
801 p_ccb->ble_sdu = NULL;
802 p_ccb->ble_sdu_length = 0;
803 p_ccb->is_first_seg = true;
804 p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
805
806 p_ccb->connection_initiator = L2CAP_INITIATOR_REMOTE;
807
808 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_REQ, &con_info);
809 } break;
810
811 case L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES: {
812 tL2C_CONN_INFO con_info{};
813 log::verbose("Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES");
814 /* For all channels, see whose identifier matches this id */
815 for (temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb;
816 temp_p_ccb = temp_p_ccb->p_next_ccb) {
817 if (temp_p_ccb->local_id == id) {
818 p_ccb = temp_p_ccb;
819 break;
820 }
821 }
822 if (p_ccb) {
823 log::verbose("I remember the connection req");
824 if (p + 10 > p_pkt_end) {
825 log::error("invalid read");
826 return;
827 }
828
829 STREAM_TO_UINT16(p_ccb->remote_cid, p);
830 STREAM_TO_UINT16(p_ccb->peer_conn_cfg.mtu, p);
831 STREAM_TO_UINT16(p_ccb->peer_conn_cfg.mps, p);
832 STREAM_TO_UINT16(p_ccb->peer_conn_cfg.credits, p);
833 uint16_t result_u16;
834 STREAM_TO_UINT16(result_u16, p);
835 con_info.l2cap_result = static_cast<tL2CAP_CONN>(result_u16);
836 con_info.remote_cid = p_ccb->remote_cid;
837
838 log::verbose(
839 "remote_cid = {}, mtu = {}, mps = {}, initial_credit = {}, "
840 "con_info.l2cap_result = {}",
841 p_ccb->remote_cid, p_ccb->peer_conn_cfg.mtu, p_ccb->peer_conn_cfg.mps,
842 p_ccb->peer_conn_cfg.credits, con_info.l2cap_result);
843
844 /* validate the parameters */
845 if (p_ccb->peer_conn_cfg.mtu < L2CAP_LE_MIN_MTU ||
846 p_ccb->peer_conn_cfg.mps < L2CAP_LE_MIN_MPS ||
847 p_ccb->peer_conn_cfg.mps > L2CAP_LE_MAX_MPS) {
848 log::error("L2CAP do not like the params");
849 con_info.l2cap_result =
850 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES);
851 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
852 break;
853 }
854
855 p_ccb->tx_mps = p_ccb->peer_conn_cfg.mps;
856 p_ccb->ble_sdu = NULL;
857 p_ccb->ble_sdu_length = 0;
858 p_ccb->is_first_seg = true;
859 p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
860
861 if (con_info.l2cap_result ==
862 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_CONN_OK)) {
863 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP, &con_info);
864 } else {
865 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
866 }
867 } else {
868 log::verbose("I DO NOT remember the connection req");
869 con_info.l2cap_result =
870 static_cast<tL2CAP_CONN>(tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INVALID_SOURCE_CID);
871 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
872 }
873 } break;
874
875 case L2CAP_CMD_BLE_FLOW_CTRL_CREDIT:
876 if (p + 4 > p_pkt_end) {
877 log::error("invalid read");
878 return;
879 }
880
881 STREAM_TO_UINT16(lcid, p);
882 p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, lcid);
883 if (p_ccb == NULL) {
884 log::verbose("Credit received for unknown channel id {}", lcid);
885 break;
886 }
887
888 STREAM_TO_UINT16(credit, p);
889 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT, &credit);
890 log::verbose("Credit received");
891 break;
892
893 case L2CAP_CMD_DISC_REQ:
894 if (p + 4 > p_pkt_end) {
895 return;
896 }
897 STREAM_TO_UINT16(lcid, p);
898 STREAM_TO_UINT16(rcid, p);
899
900 p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
901 if (p_ccb != NULL) {
902 if (p_ccb->remote_cid == rcid) {
903 p_ccb->remote_id = id;
904 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_REQ, NULL);
905 }
906 } else {
907 l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_INVALID_CID, id, 0, 0);
908 }
909
910 break;
911
912 case L2CAP_CMD_DISC_RSP:
913 if (p + 4 > p_pkt_end) {
914 log::error("invalid read");
915 return;
916 }
917 STREAM_TO_UINT16(rcid, p);
918 STREAM_TO_UINT16(lcid, p);
919
920 p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
921 if (p_ccb != NULL) {
922 if ((p_ccb->remote_cid == rcid) && (p_ccb->local_id == id)) {
923 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_RSP, NULL);
924 }
925 }
926 break;
927
928 default:
929 log::warn("L2CAP - LE - unknown cmd code: {}", cmd_code);
930 l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
931 break;
932 }
933 }
934
935 /** This function is to initiate a direct connection. Returns true if connection
936 * initiated, false otherwise. */
l2cble_create_conn(tL2C_LCB * p_lcb)937 bool l2cble_create_conn(tL2C_LCB* p_lcb) {
938 if (!connection_manager::create_le_connection(CONN_MGR_ID_L2CAP, p_lcb->remote_bd_addr)) {
939 return false;
940 }
941
942 p_lcb->link_state = LST_CONNECTING;
943
944 // TODO: we should not need this timer at all, the connection failure should
945 // be reported from lower layer
946 alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_BLE_LINK_CONNECT_TIMEOUT_MS, l2c_lcb_timer_timeout,
947 p_lcb);
948 return true;
949 }
950
951 /*******************************************************************************
952 *
953 * Function l2c_link_process_ble_num_bufs
954 *
955 * Description This function is called when a "controller buffer size"
956 * event is first received from the controller. It updates
957 * the L2CAP values.
958 *
959 * Returns void
960 *
961 ******************************************************************************/
l2c_link_process_ble_num_bufs(uint16_t num_lm_ble_bufs)962 void l2c_link_process_ble_num_bufs(uint16_t num_lm_ble_bufs) {
963 if (num_lm_ble_bufs == 0) {
964 num_lm_ble_bufs = L2C_DEF_NUM_BLE_BUF_SHARED;
965 l2cb.num_lm_acl_bufs -= L2C_DEF_NUM_BLE_BUF_SHARED;
966 }
967
968 l2cb.num_lm_ble_bufs = num_lm_ble_bufs;
969 l2cb.controller_le_xmit_window = num_lm_ble_bufs;
970 }
971
972 /*******************************************************************************
973 *
974 * Function l2c_ble_link_adjust_allocation
975 *
976 * Description This function is called when a link is created or removed
977 * to calculate the amount of packets each link may send to
978 * the HCI without an ack coming back.
979 *
980 * Currently, this is a simple allocation, dividing the
981 * number of Controller Packets by the number of links. In
982 * the future, QOS configuration should be examined.
983 *
984 * Returns void
985 *
986 ******************************************************************************/
l2c_ble_link_adjust_allocation(void)987 void l2c_ble_link_adjust_allocation(void) {
988 uint16_t qq, yy, qq_remainder;
989 tL2C_LCB* p_lcb;
990 uint16_t hi_quota, low_quota;
991 uint16_t num_lowpri_links = 0;
992 uint16_t num_hipri_links = 0;
993 uint16_t controller_xmit_quota = l2cb.num_lm_ble_bufs;
994 uint16_t high_pri_link_quota = L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A;
995
996 /* If no links active, reset buffer quotas and controller buffers */
997 if (l2cb.num_ble_links_active == 0) {
998 l2cb.controller_le_xmit_window = l2cb.num_lm_ble_bufs;
999 l2cb.ble_round_robin_quota = l2cb.ble_round_robin_unacked = 0;
1000 return;
1001 }
1002
1003 /* First, count the links */
1004 for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) {
1005 if (p_lcb->in_use && p_lcb->transport == BT_TRANSPORT_LE) {
1006 if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) {
1007 num_hipri_links++;
1008 } else {
1009 num_lowpri_links++;
1010 }
1011 }
1012 }
1013
1014 /* now adjust high priority link quota */
1015 low_quota = num_lowpri_links ? 1 : 0;
1016 while ((num_hipri_links * high_pri_link_quota + low_quota) > controller_xmit_quota) {
1017 high_pri_link_quota--;
1018 }
1019
1020 /* Work out the xmit quota and buffer quota high and low priorities */
1021 hi_quota = num_hipri_links * high_pri_link_quota;
1022 low_quota = (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1;
1023
1024 /* Work out and save the HCI xmit quota for each low priority link */
1025
1026 /* If each low priority link cannot have at least one buffer */
1027 if (num_lowpri_links > low_quota) {
1028 l2cb.ble_round_robin_quota = low_quota;
1029 qq = qq_remainder = 0;
1030 } else if (num_lowpri_links > 0) {
1031 /* If each low priority link can have at least one buffer */
1032 l2cb.ble_round_robin_quota = 0;
1033 l2cb.ble_round_robin_unacked = 0;
1034 qq = low_quota / num_lowpri_links;
1035 qq_remainder = low_quota % num_lowpri_links;
1036 } else {
1037 /* If no low priority link */
1038 l2cb.ble_round_robin_quota = 0;
1039 l2cb.ble_round_robin_unacked = 0;
1040 qq = qq_remainder = 0;
1041 }
1042 log::verbose(
1043 "l2c_ble_link_adjust_allocation num_hipri: {} num_lowpri: {} "
1044 "low_quota: {} round_robin_quota: {} qq: {}",
1045 num_hipri_links, num_lowpri_links, low_quota, l2cb.ble_round_robin_quota, qq);
1046
1047 /* Now, assign the quotas to each link */
1048 for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) {
1049 if (p_lcb->in_use && p_lcb->transport == BT_TRANSPORT_LE) {
1050 if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) {
1051 p_lcb->link_xmit_quota = high_pri_link_quota;
1052 } else {
1053 /* Safety check in case we switched to round-robin with something
1054 * outstanding */
1055 /* if sent_not_acked is added into round_robin_unacked then do not add
1056 * it again */
1057 /* l2cap keeps updating sent_not_acked for exiting from round robin */
1058 if ((p_lcb->link_xmit_quota > 0) && (qq == 0)) {
1059 l2cb.ble_round_robin_unacked += p_lcb->sent_not_acked;
1060 }
1061
1062 p_lcb->link_xmit_quota = qq;
1063 if (qq_remainder > 0) {
1064 p_lcb->link_xmit_quota++;
1065 qq_remainder--;
1066 }
1067 }
1068
1069 log::verbose("l2c_ble_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}", yy,
1070 p_lcb->acl_priority, p_lcb->link_xmit_quota);
1071
1072 log::verbose("SentNotAcked: {} RRUnacked: {}", p_lcb->sent_not_acked,
1073 l2cb.round_robin_unacked);
1074
1075 /* There is a special case where we have readjusted the link quotas and */
1076 /* this link may have sent anything but some other link sent packets so */
1077 /* so we may need a timer to kick off this link's transmissions. */
1078 if (p_lcb->link_xmit_data_q != nullptr) {
1079 if ((p_lcb->link_state == LST_CONNECTED) &&
1080 !list_is_empty(p_lcb->link_xmit_data_q) &&
1081 (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) {
1082 alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS,
1083 l2c_lcb_timer_timeout, p_lcb);
1084 }
1085 } else {
1086 log::warn("link_xmit_data_q is null");
1087 }
1088 }
1089 }
1090 }
1091
1092 /*******************************************************************************
1093 *
1094 * Function l2cble_update_data_length
1095 *
1096 * Description This function update link tx data length if applicable
1097 *
1098 * Returns void
1099 *
1100 ******************************************************************************/
l2cble_update_data_length(tL2C_LCB * p_lcb)1101 void l2cble_update_data_length(tL2C_LCB* p_lcb) {
1102 uint16_t tx_mtu = 0;
1103 uint16_t i = 0;
1104
1105 log::verbose("");
1106
1107 /* See if we have a link control block for the connection */
1108 if (p_lcb == NULL) {
1109 return;
1110 }
1111
1112 for (i = 0; i < L2CAP_NUM_FIXED_CHNLS; i++) {
1113 if (i + L2CAP_FIRST_FIXED_CHNL != L2CAP_BLE_SIGNALLING_CID) {
1114 if ((p_lcb->p_fixed_ccbs[i] != NULL) &&
1115 (tx_mtu < (p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD))) {
1116 tx_mtu = p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD;
1117 }
1118 }
1119 }
1120
1121 if (tx_mtu > BTM_BLE_DATA_SIZE_MAX) {
1122 tx_mtu = BTM_BLE_DATA_SIZE_MAX;
1123 }
1124
1125 /* update TX data length if changed */
1126 if (p_lcb->tx_data_len != tx_mtu) {
1127 if (get_btm_client_interface().ble.BTM_SetBleDataLength(p_lcb->remote_bd_addr, tx_mtu) !=
1128 tBTM_STATUS::BTM_SUCCESS) {
1129 log::warn("Unable to set BLE data length peer:{} mtu:{}", p_lcb->remote_bd_addr, tx_mtu);
1130 }
1131 }
1132 }
1133
1134 /*******************************************************************************
1135 *
1136 * Function l2cble_process_data_length_change_evt
1137 *
1138 * Description This function process the data length change event
1139 *
1140 * Returns void
1141 *
1142 ******************************************************************************/
is_legal_tx_data_len(const uint16_t & tx_data_len)1143 static bool is_legal_tx_data_len(const uint16_t& tx_data_len) {
1144 return tx_data_len >= 0x001B && tx_data_len <= 0x00FB;
1145 }
1146
l2cble_process_data_length_change_event(uint16_t handle,uint16_t tx_data_len,uint16_t)1147 void l2cble_process_data_length_change_event(uint16_t handle, uint16_t tx_data_len,
1148 uint16_t /* rx_data_len */) {
1149 tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
1150 if (p_lcb == nullptr) {
1151 log::warn("Received data length change event for unknown ACL handle:0x{:04x}", handle);
1152 return;
1153 }
1154
1155 if (is_legal_tx_data_len(tx_data_len)) {
1156 if (p_lcb->tx_data_len != tx_data_len) {
1157 log::debug(
1158 "Received data length change event for device:{} tx_data_len:{} => "
1159 "{}",
1160 p_lcb->remote_bd_addr, p_lcb->tx_data_len, tx_data_len);
1161 BTM_LogHistory(kBtmLogTag, p_lcb->remote_bd_addr, "LE Data length change",
1162 base::StringPrintf("tx_octets:%hu => %hu", p_lcb->tx_data_len, tx_data_len));
1163 p_lcb->tx_data_len = tx_data_len;
1164 } else {
1165 log::debug(
1166 "Received duplicated data length change event for device:{} "
1167 "tx_data_len:{}",
1168 p_lcb->remote_bd_addr, tx_data_len);
1169 }
1170 } else {
1171 log::warn(
1172 "Received illegal data length change event for device:{} "
1173 "tx_data_len:{}",
1174 p_lcb->remote_bd_addr, tx_data_len);
1175 }
1176 /* ignore rx_data len for now */
1177 }
1178
1179 /*******************************************************************************
1180 *
1181 * Function l2cble_credit_based_conn_req
1182 *
1183 * Description This function sends LE Credit Based Connection Request for
1184 * LE connection oriented channels.
1185 *
1186 * Returns void
1187 *
1188 ******************************************************************************/
l2cble_credit_based_conn_req(tL2C_CCB * p_ccb)1189 void l2cble_credit_based_conn_req(tL2C_CCB* p_ccb) {
1190 if (!p_ccb) {
1191 return;
1192 }
1193
1194 if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
1195 log::warn("LE link doesn't exist");
1196 return;
1197 }
1198
1199 if (p_ccb->ecoc) {
1200 l2cu_send_peer_credit_based_conn_req(p_ccb);
1201 } else {
1202 l2cu_send_peer_ble_credit_based_conn_req(p_ccb);
1203 }
1204 return;
1205 }
1206
1207 /*******************************************************************************
1208 *
1209 * Function l2cble_credit_based_conn_res
1210 *
1211 * Description This function sends LE Credit Based Connection Response for
1212 * LE connection oriented channels.
1213 *
1214 * Returns void
1215 *
1216 ******************************************************************************/
l2cble_credit_based_conn_res(tL2C_CCB * p_ccb,tL2CAP_LE_RESULT_CODE result)1217 void l2cble_credit_based_conn_res(tL2C_CCB* p_ccb, tL2CAP_LE_RESULT_CODE result) {
1218 if (!p_ccb) {
1219 return;
1220 }
1221
1222 if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
1223 log::warn("LE link doesn't exist");
1224 return;
1225 }
1226
1227 l2cu_send_peer_ble_credit_based_conn_res(p_ccb, result);
1228 return;
1229 }
1230
1231 /*******************************************************************************
1232 *
1233 * Function l2cble_send_flow_control_credit
1234 *
1235 * Description This function sends flow control credits for
1236 * LE connection oriented channels.
1237 *
1238 * Returns void
1239 *
1240 ******************************************************************************/
l2cble_send_flow_control_credit(tL2C_CCB * p_ccb,uint16_t credit_value)1241 void l2cble_send_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value) {
1242 if (!p_ccb) {
1243 return;
1244 }
1245
1246 if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
1247 log::warn("LE link doesn't exist");
1248 return;
1249 }
1250
1251 l2cu_send_peer_ble_flow_control_credit(p_ccb, credit_value);
1252 return;
1253 }
1254
1255 /*******************************************************************************
1256 *
1257 * Function l2cble_send_peer_disc_req
1258 *
1259 * Description This function sends disconnect request
1260 * to the peer LE device
1261 *
1262 * Returns void
1263 *
1264 ******************************************************************************/
l2cble_send_peer_disc_req(tL2C_CCB * p_ccb)1265 void l2cble_send_peer_disc_req(tL2C_CCB* p_ccb) {
1266 log::verbose("");
1267 if (!p_ccb) {
1268 return;
1269 }
1270
1271 if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE) {
1272 log::warn("LE link doesn't exist");
1273 return;
1274 }
1275
1276 l2cu_send_peer_ble_credit_based_disconn_req(p_ccb);
1277 return;
1278 }
1279
1280 /*******************************************************************************
1281 *
1282 * Function l2cble_sec_comp
1283 *
1284 * Description This function is called when security procedure for an LE
1285 * COC link is done
1286 *
1287 * Returns void
1288 *
1289 ******************************************************************************/
l2cble_sec_comp(RawAddress bda,tBT_TRANSPORT transport,void *,tBTM_STATUS btm_status)1290 static void l2cble_sec_comp(RawAddress bda, tBT_TRANSPORT transport, void* /* p_ref_data */,
1291 tBTM_STATUS btm_status) {
1292 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
1293 tL2CAP_SEC_DATA* p_buf = NULL;
1294 uint8_t sec_act;
1295
1296 if (!p_lcb) {
1297 log::warn("security complete for unknown device. bda={}", bda);
1298 return;
1299 }
1300
1301 sec_act = p_lcb->sec_act;
1302 p_lcb->sec_act = 0;
1303
1304 if (!fixed_queue_is_empty(p_lcb->le_sec_pending_q)) {
1305 p_buf = (tL2CAP_SEC_DATA*)fixed_queue_dequeue(p_lcb->le_sec_pending_q);
1306 if (!p_buf) {
1307 log::warn("Security complete for request not initiated from L2CAP");
1308 return;
1309 }
1310
1311 if (btm_status != tBTM_STATUS::BTM_SUCCESS) {
1312 (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, btm_status);
1313 osi_free(p_buf);
1314 } else {
1315 if (sec_act == BTM_SEC_ENCRYPT_MITM) {
1316 if (BTM_IsLinkKeyAuthed(bda, transport)) {
1317 (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, btm_status);
1318 } else {
1319 log::verbose("MITM Protection Not present");
1320 (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data,
1321 tBTM_STATUS::BTM_FAILED_ON_SECURITY);
1322 }
1323 } else {
1324 log::verbose("MITM Protection not required sec_act = {}", p_lcb->sec_act);
1325
1326 (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, btm_status);
1327 }
1328 osi_free(p_buf);
1329 }
1330 } else {
1331 log::warn("Security complete for request not initiated from L2CAP");
1332 return;
1333 }
1334
1335 while (!fixed_queue_is_empty(p_lcb->le_sec_pending_q)) {
1336 p_buf = (tL2CAP_SEC_DATA*)fixed_queue_dequeue(p_lcb->le_sec_pending_q);
1337
1338 if (btm_status != tBTM_STATUS::BTM_SUCCESS) {
1339 (*(p_buf->p_callback))(bda, BT_TRANSPORT_LE, p_buf->p_ref_data, btm_status);
1340 osi_free(p_buf);
1341 } else {
1342 l2ble_sec_access_req(bda, p_buf->psm, p_buf->is_originator, p_buf->p_callback,
1343 p_buf->p_ref_data);
1344
1345 osi_free(p_buf);
1346 break;
1347 }
1348 }
1349 }
1350
1351 /*******************************************************************************
1352 *
1353 * Function l2ble_sec_access_req
1354 *
1355 * Description This function is called by LE COC link to meet the
1356 * security requirement for the link
1357 *
1358 * Returns Returns - L2CAP LE Connection Response Result Code.
1359 *
1360 ******************************************************************************/
l2ble_sec_access_req(const RawAddress & bd_addr,uint16_t psm,bool is_originator,tBTM_SEC_CALLBACK * p_callback,void * p_ref_data)1361 tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, uint16_t psm,
1362 bool is_originator, tBTM_SEC_CALLBACK* p_callback,
1363 void* p_ref_data) {
1364 tL2C_LCB* p_lcb = NULL;
1365
1366 if (!p_callback) {
1367 log::error("No callback function");
1368 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES;
1369 }
1370
1371 p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
1372
1373 if (!p_lcb) {
1374 log::error("Security check for unknown device");
1375 p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, tBTM_STATUS::BTM_UNKNOWN_ADDR);
1376 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES;
1377 }
1378
1379 tL2CAP_SEC_DATA* p_buf = (tL2CAP_SEC_DATA*)osi_malloc((uint16_t)sizeof(tL2CAP_SEC_DATA));
1380 if (!p_buf) {
1381 log::error("No resources for connection");
1382 p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, tBTM_STATUS::BTM_NO_RESOURCES);
1383 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_RESOURCES;
1384 }
1385
1386 p_buf->psm = psm;
1387 p_buf->is_originator = is_originator;
1388 p_buf->p_callback = p_callback;
1389 p_buf->p_ref_data = p_ref_data;
1390 fixed_queue_enqueue(p_lcb->le_sec_pending_q, p_buf);
1391 tBTM_STATUS result =
1392 btm_ble_start_sec_check(bd_addr, psm, is_originator, &l2cble_sec_comp, p_ref_data);
1393
1394 switch (result) {
1395 case tBTM_STATUS::BTM_SUCCESS:
1396 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_CONN_OK;
1397 case tBTM_STATUS::BTM_ILLEGAL_VALUE:
1398 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_NO_PSM;
1399 case tBTM_STATUS::BTM_NOT_AUTHENTICATED:
1400 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION;
1401 case tBTM_STATUS::BTM_NOT_ENCRYPTED:
1402 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP;
1403 case tBTM_STATUS::BTM_NOT_AUTHORIZED:
1404 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_AUTHORIZATION;
1405 case tBTM_STATUS::BTM_INSUFFICIENT_ENCRYPT_KEY_SIZE:
1406 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP_KEY_SIZE;
1407 default:
1408 log::error("unexpected return value: {}", btm_status_text(result));
1409 return tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INVALID_PARAMETERS;
1410 }
1411 }
1412
1413 /* This function is called to adjust the connection intervals based on various
1414 * constraints. For example, when there is at least one Hearing Aid device
1415 * bonded, the minimum interval is raised. On return, min_interval and
1416 * max_interval are updated. */
L2CA_AdjustConnectionIntervals(uint16_t * min_interval,uint16_t * max_interval,uint16_t floor_interval)1417 void L2CA_AdjustConnectionIntervals(uint16_t* min_interval, uint16_t* max_interval,
1418 uint16_t floor_interval) {
1419 // Allow for customization by systemprops for mainline
1420 uint16_t phone_min_interval = floor_interval;
1421 #ifdef __ANDROID__
1422 phone_min_interval =
1423 android::sysprop::BluetoothProperties::getGapLeConnMinLimit().value_or(floor_interval);
1424 #else
1425 phone_min_interval = (uint16_t)osi_property_get_int32("bluetooth.core.gap.le.conn.min.limit",
1426 (int32_t)floor_interval);
1427 #endif
1428
1429 if (GetInterfaceToProfiles()->profileSpecific_HACK->GetHearingAidDeviceCount()) {
1430 // When there are bonded Hearing Aid devices, we will constrained this
1431 // minimum interval.
1432 phone_min_interval = BTM_BLE_CONN_INT_MIN_HEARINGAID;
1433 log::verbose("Have Hearing Aids. Min. interval is set to {}", phone_min_interval);
1434 }
1435
1436 if (!com::android::bluetooth::flags::l2cap_le_do_not_adjust_min_interval() &&
1437 *min_interval < phone_min_interval) {
1438 log::verbose("requested min_interval={} too small. Set to {}", *min_interval,
1439 phone_min_interval);
1440 *min_interval = phone_min_interval;
1441 }
1442
1443 // While this could result in connection parameters that fall
1444 // outside fo the range requested, this will allow the connection
1445 // to remain established.
1446 // In other words, this is a workaround for certain peripherals.
1447 if (*max_interval < phone_min_interval) {
1448 log::verbose("requested max_interval={} too small. Set to {}", *max_interval,
1449 phone_min_interval);
1450 *max_interval = phone_min_interval;
1451 }
1452 }
1453
L2CA_SetEcosystemBaseInterval(uint32_t base_interval)1454 void L2CA_SetEcosystemBaseInterval(uint32_t base_interval) {
1455 if (!com::android::bluetooth::flags::le_audio_base_ecosystem_interval()) {
1456 return;
1457 }
1458
1459 log::info("base_interval: {}ms", base_interval);
1460 bluetooth::shim::GetHciLayer()->EnqueueCommand(
1461 bluetooth::hci::SetEcosystemBaseIntervalBuilder::Create(base_interval),
1462 get_main_thread()->BindOnce([](bluetooth::hci::CommandCompleteView view) {
1463 ASSERT(view.IsValid());
1464 auto status_view = bluetooth::hci::SetEcosystemBaseIntervalCompleteView::Create(
1465 bluetooth::hci::SetEcosystemBaseIntervalCompleteView::Create(view));
1466 ASSERT(status_view.IsValid());
1467
1468 if (status_view.GetStatus() != bluetooth::hci::ErrorCode::SUCCESS) {
1469 log::warn("Set Ecosystem Base Interval status {}",
1470 ErrorCodeText(status_view.GetStatus()));
1471 return;
1472 }
1473 }));
1474
1475 if (com::android::bluetooth::flags::l2cap_update_existing_conn_interval_with_base_interval() &&
1476 base_interval != 0) {
1477 tL2C_LCB* p_lcb = &l2cb.lcb_pool[0];
1478
1479 for (int i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) {
1480 if ((p_lcb->in_use) && p_lcb->transport == BT_TRANSPORT_LE) {
1481 bool ret = L2CA_UpdateBleConnParams(p_lcb->remote_bd_addr, p_lcb->min_interval,
1482 p_lcb->max_interval, p_lcb->latency, p_lcb->timeout,
1483 p_lcb->min_ce_len, p_lcb->max_ce_len);
1484 if (!ret) {
1485 log::warn("Unable to update BLE connection parameters peer:{}", p_lcb->remote_bd_addr);
1486 }
1487 }
1488 }
1489 }
1490 }
1491