1 /******************************************************************************
2 *
3 * Copyright 1999-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 the functions relating to link management. A "link"
22 * is a connection between this device and another device. Only ACL links
23 * are managed.
24 *
25 ******************************************************************************/
26 #define LOG_TAG "l2c_link"
27
28 #include <bluetooth/log.h>
29 #include <com_android_bluetooth_flags.h>
30
31 #include <cstdint>
32
33 #include "device/include/device_iot_config.h"
34 #include "internal_include/bt_target.h"
35 #include "osi/include/allocator.h"
36 #include "stack/btm/btm_int_types.h"
37 #include "stack/include/acl_api.h"
38 #include "stack/include/bt_hdr.h"
39 #include "stack/include/bt_types.h"
40 #include "stack/include/btm_status.h"
41 #include "stack/include/hci_error_code.h"
42 #include "stack/include/l2cap_acl_interface.h"
43 #include "stack/include/l2cap_controller_interface.h"
44 #include "stack/include/l2cap_hci_link_interface.h"
45 #include "stack/include/l2cap_security_interface.h"
46 #include "stack/l2cap/l2c_int.h"
47 #include "types/bt_transport.h"
48 #include "types/raw_address.h"
49
50 using namespace bluetooth;
51
52 extern tBTM_CB btm_cb;
53
54 bool BTM_ReadPowerMode(const RawAddress& remote_bda, tBTM_PM_MODE* p_mode);
55 tBTM_STATUS btm_sec_disconnect(uint16_t handle, tHCI_STATUS reason, std::string);
56 void btm_acl_created(const RawAddress& bda, uint16_t hci_handle, uint8_t link_role,
57 tBT_TRANSPORT transport);
58 void btm_acl_removed(uint16_t handle);
59 void btm_ble_decrement_link_topology_mask(uint8_t link_role);
60 void btm_sco_acl_removed(const RawAddress* bda);
61
62 static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf, tL2C_TX_COMPLETE_CB_INFO* p_cbi);
63 static BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, tL2C_TX_COMPLETE_CB_INFO* p_cbi);
64
l2c_link_hci_conn_comp(tHCI_STATUS status,uint16_t handle,const RawAddress & p_bda)65 void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, const RawAddress& p_bda) {
66 tL2C_CCB* p_ccb;
67
68 /* Save the parameters */
69 tL2C_CONN_INFO ci = {
70 .bd_addr = p_bda,
71 .hci_status = status,
72 .psm{},
73 .l2cap_result{},
74 .l2cap_status{},
75 .remote_cid{},
76 .lcids{},
77 .peer_mtu{},
78 };
79
80 /* See if we have a link control block for the remote device */
81 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(ci.bd_addr, BT_TRANSPORT_BR_EDR);
82 if (p_lcb == nullptr) {
83 /* If we don't have one, allocate one */
84 p_lcb = l2cu_allocate_lcb(ci.bd_addr, false, BT_TRANSPORT_BR_EDR);
85 if (p_lcb == nullptr) {
86 log::warn("Failed to allocate an LCB");
87 return;
88 }
89 log::debug("Allocated l2cap control block for new connection state:{}",
90 link_state_text(p_lcb->link_state));
91 p_lcb->link_state = LST_CONNECTING;
92 }
93
94 if ((p_lcb->link_state == LST_CONNECTED) && (status == HCI_ERR_CONNECTION_EXISTS)) {
95 log::warn("Connection already exists handle:0x{:04x}", handle);
96 return;
97 } else if (p_lcb->link_state != LST_CONNECTING) {
98 log::error(
99 "Link received unexpected connection complete state:{} status:{} "
100 "handle:0x{:04x}",
101 link_state_text(p_lcb->link_state), hci_error_code_text(status), p_lcb->Handle());
102 if (status != HCI_SUCCESS) {
103 log::error("Disconnecting...");
104 l2c_link_hci_disc_comp(p_lcb->Handle(), status);
105 }
106 return;
107 }
108
109 /* Save the handle */
110 l2cu_set_lcb_handle(*p_lcb, handle);
111
112 if (ci.hci_status == HCI_SUCCESS) {
113 /* Connected OK. Change state to connected */
114 p_lcb->link_state = LST_CONNECTED;
115
116 /* Get the peer information if the l2cap flow-control/rtrans is supported */
117 l2cu_send_peer_info_req(p_lcb, L2CAP_EXTENDED_FEATURES_INFO_TYPE);
118
119 if (p_lcb->IsBonding()) {
120 log::debug("Link is dedicated bonding handle:0x{:04x}", p_lcb->Handle());
121 if (l2cu_start_post_bond_timer(handle)) {
122 return;
123 }
124 }
125
126 alarm_cancel(p_lcb->l2c_lcb_timer);
127
128 /* For all channels, send the event through their FSMs */
129 for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) {
130 l2c_csm_execute(p_ccb, L2CEVT_LP_CONNECT_CFM, &ci);
131 }
132
133 if (!p_lcb->ccb_queue.p_first_ccb) {
134 uint64_t timeout_ms = L2CAP_LINK_STARTUP_TOUT * 1000;
135 alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, p_lcb);
136 }
137 } else if ((ci.hci_status == HCI_ERR_MAX_NUM_OF_CONNECTIONS) && l2cu_lcb_disconnecting()) {
138 /* Max number of acl connections. */
139 /* If there's an lcb disconnecting set this one to holding */
140 log::warn("Delaying connection as reached max number of links:{}",
141 HCI_ERR_MAX_NUM_OF_CONNECTIONS);
142 p_lcb->link_state = LST_CONNECT_HOLDING;
143 p_lcb->InvalidateHandle();
144 } else {
145 /* Just in case app decides to try again in the callback context */
146 p_lcb->link_state = LST_DISCONNECTING;
147
148 /* Connection failed. For all channels, send the event through */
149 /* their FSMs. The CCBs should remove themselves from the LCB */
150 for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb;) {
151 tL2C_CCB* pn = p_ccb->p_next_ccb;
152
153 l2c_csm_execute(p_ccb, L2CEVT_LP_CONNECT_CFM_NEG, &ci);
154
155 p_ccb = pn;
156 }
157
158 log::info("Disconnecting link handle:0x{:04x} status:{}", p_lcb->Handle(),
159 hci_error_code_text(status));
160 p_lcb->SetDisconnectReason(status);
161 /* Release the LCB */
162 if (p_lcb->ccb_queue.p_first_ccb == NULL) {
163 l2cu_release_lcb(p_lcb);
164 } else /* there are any CCBs remaining */
165 {
166 if (ci.hci_status == HCI_ERR_CONNECTION_EXISTS) {
167 /* we are in collision situation, wait for connecttion request from
168 * controller */
169 p_lcb->link_state = LST_CONNECTING;
170 } else {
171 l2cu_create_conn_br_edr(p_lcb);
172 }
173 }
174 }
175 }
176
177 /*******************************************************************************
178 *
179 * Function l2c_link_sec_comp
180 *
181 * Description This function is called when required security procedures
182 * are completed.
183 *
184 * Returns void
185 *
186 ******************************************************************************/
l2c_link_sec_comp(RawAddress p_bda,tBT_TRANSPORT transport,void * p_ref_data,tBTM_STATUS btm_status)187 void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, void* p_ref_data,
188 tBTM_STATUS btm_status) {
189 tL2C_CCB* p_ccb;
190 tL2C_CCB* p_next_ccb;
191
192 log::debug("btm_status={}, BD_ADDR={}, transport={}", btm_status_text(btm_status), p_bda,
193 bt_transport_text(transport));
194
195 if (btm_status == tBTM_STATUS::BTM_SUCCESS_NO_SECURITY) {
196 btm_status = tBTM_STATUS::BTM_SUCCESS;
197 }
198
199 /* Save the parameters */
200 tL2C_CONN_INFO ci = {
201 .bd_addr = p_bda,
202 .hci_status = static_cast<tHCI_STATUS>(btm_status),
203 .psm{},
204 .l2cap_result{},
205 .l2cap_status{},
206 .remote_cid{},
207 .lcids{},
208 .peer_mtu{},
209 };
210
211 /* If we don't have one, this is an error */
212 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bda, transport);
213 if (!p_lcb) {
214 log::warn("L2CAP got sec_comp for unknown BD_ADDR");
215 return;
216 }
217
218 if (com::android::bluetooth::flags::l2cap_p_ccb_check_rewrite()) {
219 if (!p_ref_data) {
220 log::warn("Argument p_ref_data is NULL");
221 return;
222 }
223
224 /* Match p_ccb with p_ref_data returned by sec manager */
225 p_ccb = (tL2C_CCB*)p_ref_data;
226
227 if (p_lcb != p_ccb->p_lcb) {
228 log::warn("p_ref_data doesn't match with sec manager record");
229 return;
230 }
231
232 switch (btm_status) {
233 case tBTM_STATUS::BTM_SUCCESS:
234 l2c_csm_execute(p_ccb, L2CEVT_SEC_COMP, &ci);
235 break;
236
237 case tBTM_STATUS::BTM_DELAY_CHECK:
238 /* start a timer - encryption change not received before L2CAP connect
239 * req */
240 alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS,
241 l2c_ccb_timer_timeout, p_ccb);
242 return;
243
244 default:
245 l2c_csm_execute(p_ccb, L2CEVT_SEC_COMP_NEG, &ci);
246 break;
247 }
248 } else {
249 /* Match p_ccb with p_ref_data returned by sec manager */
250 for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_next_ccb) {
251 p_next_ccb = p_ccb->p_next_ccb;
252
253 if (p_ccb == p_ref_data) {
254 switch (btm_status) {
255 case tBTM_STATUS::BTM_SUCCESS:
256 l2c_csm_execute(p_ccb, L2CEVT_SEC_COMP, &ci);
257 break;
258
259 case tBTM_STATUS::BTM_DELAY_CHECK:
260 /* start a timer - encryption change not received before L2CAP
261 * connect req */
262 alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS,
263 l2c_ccb_timer_timeout, p_ccb);
264 return;
265
266 default:
267 l2c_csm_execute(p_ccb, L2CEVT_SEC_COMP_NEG, &ci);
268 break;
269 }
270 }
271 }
272 }
273 }
274
275 /*******************************************************************************
276 **
277 ** Function l2c_link_iot_store_disc_reason
278 **
279 ** Description iot store disconnection reason to local conf file
280 **
281 ** Returns void
282 **
283 *******************************************************************************/
l2c_link_iot_store_disc_reason(RawAddress & bda,uint8_t reason)284 static void l2c_link_iot_store_disc_reason(RawAddress& bda, uint8_t reason) {
285 const char* disc_keys[] = {
286 IOT_CONF_KEY_GAP_DISC_CONNTIMEOUT_COUNT,
287 };
288 const uint8_t disc_reasons[] = {
289 HCI_ERR_CONNECTION_TOUT,
290 };
291 int i = 0;
292 int num = sizeof(disc_keys) / sizeof(disc_keys[0]);
293
294 if (reason == (uint8_t)-1) {
295 return;
296 }
297
298 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(bda, IOT_CONF_KEY_GAP_DISC_COUNT);
299 for (i = 0; i < num; i++) {
300 if (disc_reasons[i] == reason) {
301 DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(bda, disc_keys[i]);
302 break;
303 }
304 }
305 }
306
307 /*******************************************************************************
308 *
309 * Function l2c_link_hci_disc_comp
310 *
311 * Description This function is called when an HCI Disconnect Complete
312 * event is received.
313 *
314 * Returns true if the link is known about, else false
315 *
316 ******************************************************************************/
l2c_link_hci_disc_comp(uint16_t handle,tHCI_REASON reason)317 bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) {
318 tL2C_CCB* p_ccb;
319 bool status = true;
320 bool lcb_is_free = true;
321
322 /* If we don't have one, maybe an SCO link. Send to MM */
323 tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
324 if (!p_lcb) {
325 status = false;
326 } else {
327 l2c_link_iot_store_disc_reason(p_lcb->remote_bd_addr, reason);
328
329 p_lcb->SetDisconnectReason(reason);
330
331 /* Just in case app decides to try again in the callback context */
332 p_lcb->link_state = LST_DISCONNECTING;
333
334 /* Check for BLE and handle that differently */
335 if (p_lcb->transport == BT_TRANSPORT_LE) {
336 btm_ble_decrement_link_topology_mask(p_lcb->LinkRole());
337 }
338 /* Link is disconnected. For all channels, send the event through */
339 /* their FSMs. The CCBs should remove themselves from the LCB */
340 for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb;) {
341 tL2C_CCB* pn = p_ccb->p_next_ccb;
342
343 /* Keep connect pending control block (if exists)
344 * Possible Race condition when a reconnect occurs
345 * on the channel during a disconnect of link. This
346 * ccb will be automatically retried after link disconnect
347 * arrives
348 */
349 if (p_ccb != p_lcb->p_pending_ccb) {
350 l2c_csm_execute(p_ccb, L2CEVT_LP_DISCONNECT_IND, &reason);
351 }
352 p_ccb = pn;
353 }
354
355 if (p_lcb->transport == BT_TRANSPORT_BR_EDR) {
356 /* Tell SCO management to drop any SCOs on this ACL */
357 btm_sco_acl_removed(&p_lcb->remote_bd_addr);
358 }
359
360 /* If waiting for disconnect and reconnect is pending start the reconnect
361 now
362 race condition where layer above issued connect request on link that was
363 disconnecting
364 */
365 if (p_lcb->ccb_queue.p_first_ccb != NULL || p_lcb->p_pending_ccb) {
366 log::debug("l2c_link_hci_disc_comp: Restarting pending ACL request");
367 /* Release any held buffers */
368 while (!list_is_empty(p_lcb->link_xmit_data_q)) {
369 BT_HDR* p_buf = static_cast<BT_HDR*>(list_front(p_lcb->link_xmit_data_q));
370 list_remove(p_lcb->link_xmit_data_q, p_buf);
371 osi_free(p_buf);
372 }
373 /* for LE link, always drop and re-open to ensure to get LE remote feature
374 */
375 if (p_lcb->transport == BT_TRANSPORT_LE) {
376 btm_acl_removed(handle);
377 } else {
378 /* If we are going to re-use the LCB without dropping it, release all
379 fixed channels
380 here */
381 int xx;
382 for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) {
383 if (p_lcb->p_fixed_ccbs[xx] && p_lcb->p_fixed_ccbs[xx] != p_lcb->p_pending_ccb) {
384 l2cu_release_ccb(p_lcb->p_fixed_ccbs[xx]);
385
386 p_lcb->p_fixed_ccbs[xx] = NULL;
387 (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL,
388 p_lcb->remote_bd_addr, false,
389 p_lcb->DisconnectReason(), p_lcb->transport);
390 }
391 }
392 /* Cleanup connection state to avoid race conditions because
393 * l2cu_release_lcb won't be invoked to cleanup */
394 btm_acl_removed(p_lcb->Handle());
395 p_lcb->InvalidateHandle();
396 }
397 if (p_lcb->transport == BT_TRANSPORT_LE) {
398 if (l2cu_create_conn_le(p_lcb)) {
399 lcb_is_free = false; /* still using this lcb */
400 }
401 } else {
402 l2cu_create_conn_br_edr(p_lcb);
403 lcb_is_free = false; /* still using this lcb */
404 }
405 }
406
407 p_lcb->p_pending_ccb = NULL;
408
409 /* Release the LCB */
410 if (lcb_is_free) {
411 l2cu_release_lcb(p_lcb);
412 }
413 }
414
415 /* Now that we have a free acl connection, see if any lcbs are pending */
416 if (lcb_is_free && ((p_lcb = l2cu_find_lcb_by_state(LST_CONNECT_HOLDING)) != NULL)) {
417 /* we found one-- create a connection */
418 l2cu_create_conn_br_edr(p_lcb);
419 }
420
421 return status;
422 }
423
424 /*******************************************************************************
425 *
426 * Function l2c_link_timeout
427 *
428 * Description This function is called when a link timer expires
429 *
430 * Returns void
431 *
432 ******************************************************************************/
l2c_link_timeout(tL2C_LCB * p_lcb)433 void l2c_link_timeout(tL2C_LCB* p_lcb) {
434 tL2C_CCB* p_ccb;
435 tBTM_STATUS rc;
436
437 log::debug("L2CAP - l2c_link_timeout() link state:{} is_bonding:{}",
438 link_state_text(p_lcb->link_state), p_lcb->IsBonding());
439
440 /* If link was connecting or disconnecting, clear all channels and drop the
441 * LCB */
442 if ((p_lcb->link_state == LST_CONNECTING_WAIT_SWITCH) || (p_lcb->link_state == LST_CONNECTING) ||
443 (p_lcb->link_state == LST_CONNECT_HOLDING) || (p_lcb->link_state == LST_DISCONNECTING)) {
444 p_lcb->p_pending_ccb = NULL;
445
446 /* For all channels, send a disconnect indication event through */
447 /* their FSMs. The CCBs should remove themselves from the LCB */
448 for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb;) {
449 tL2C_CCB* pn = p_ccb->p_next_ccb;
450
451 l2c_csm_execute(p_ccb, L2CEVT_LP_DISCONNECT_IND, NULL);
452
453 p_ccb = pn;
454 }
455
456 /* Release the LCB */
457 l2cu_release_lcb(p_lcb);
458 }
459
460 /* If link is connected, check for inactivity timeout */
461 if (p_lcb->link_state == LST_CONNECTED) {
462 /* If no channels in use, drop the link. */
463 if (!p_lcb->ccb_queue.p_first_ccb) {
464 uint64_t timeout_ms;
465 bool start_timeout = true;
466
467 log::warn("TODO: Remove this callback into bcm_sec_disconnect");
468 rc = btm_sec_disconnect(p_lcb->Handle(), HCI_ERR_PEER_USER,
469 "stack::l2cap::l2c_link::l2c_link_timeout All channels closed");
470
471 if (rc == tBTM_STATUS::BTM_CMD_STORED) {
472 /* Security Manager will take care of disconnecting, state will be
473 * updated at that time */
474 start_timeout = false;
475 } else if (rc == tBTM_STATUS::BTM_CMD_STARTED) {
476 p_lcb->link_state = LST_DISCONNECTING;
477 timeout_ms = L2CAP_LINK_DISCONNECT_TIMEOUT_MS;
478 } else if (rc == tBTM_STATUS::BTM_SUCCESS) {
479 l2cu_process_fixed_disc_cback(p_lcb);
480 /* BTM SEC will make sure that link is release (probably after pairing
481 * is done) */
482 p_lcb->link_state = LST_DISCONNECTING;
483 start_timeout = false;
484 } else if (rc == tBTM_STATUS::BTM_BUSY) {
485 /* BTM is still executing security process. Let lcb stay as connected */
486 start_timeout = false;
487 } else if (p_lcb->IsBonding()) {
488 acl_disconnect_from_handle(p_lcb->Handle(), HCI_ERR_PEER_USER,
489 "stack::l2cap::l2c_link::l2c_link_timeout "
490 "Timer expired while bonding");
491 l2cu_process_fixed_disc_cback(p_lcb);
492 p_lcb->link_state = LST_DISCONNECTING;
493 timeout_ms = L2CAP_LINK_DISCONNECT_TIMEOUT_MS;
494 } else {
495 /* probably no buffer to send disconnect */
496 timeout_ms = BT_1SEC_TIMEOUT_MS;
497 }
498
499 if (start_timeout) {
500 alarm_set_on_mloop(p_lcb->l2c_lcb_timer, timeout_ms, l2c_lcb_timer_timeout, p_lcb);
501 }
502 } else {
503 /* Check in case we were flow controlled */
504 l2c_link_check_send_pkts(p_lcb, 0, NULL);
505 }
506 }
507 }
508
509 /*******************************************************************************
510 *
511 * Function l2c_info_resp_timer_timeout
512 *
513 * Description This function is called when an info request times out
514 *
515 * Returns void
516 *
517 ******************************************************************************/
l2c_info_resp_timer_timeout(void * data)518 void l2c_info_resp_timer_timeout(void* data) {
519 tL2C_LCB* p_lcb = (tL2C_LCB*)data;
520 tL2C_CCB* p_ccb;
521
522 /* If we timed out waiting for info response, just continue using basic if
523 * allowed */
524 if (p_lcb->w4_info_rsp) {
525 /* If waiting for security complete, restart the info response timer */
526 for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) {
527 if ((p_ccb->chnl_state == CST_ORIG_W4_SEC_COMP) ||
528 (p_ccb->chnl_state == CST_TERM_W4_SEC_COMP)) {
529 alarm_set_on_mloop(p_lcb->info_resp_timer, L2CAP_WAIT_INFO_RSP_TIMEOUT_MS,
530 l2c_info_resp_timer_timeout, p_lcb);
531 return;
532 }
533 }
534
535 p_lcb->w4_info_rsp = false;
536
537 /* If link is in process of being brought up */
538 if ((p_lcb->link_state != LST_DISCONNECTED) && (p_lcb->link_state != LST_DISCONNECTING)) {
539 /* Notify active channels that peer info is finished */
540 if (p_lcb->ccb_queue.p_first_ccb) {
541 tL2C_CONN_INFO ci = {
542 .bd_addr = p_lcb->remote_bd_addr,
543 .hci_status = HCI_SUCCESS,
544 .psm{},
545 .l2cap_result{},
546 .l2cap_status{},
547 .remote_cid{},
548 .lcids{},
549 .peer_mtu{},
550 };
551 for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) {
552 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_INFO_RSP, &ci);
553 }
554 }
555 }
556 }
557 }
558
559 /*******************************************************************************
560 *
561 * Function l2c_link_adjust_allocation
562 *
563 * Description This function is called when a link is created or removed
564 * to calculate the amount of packets each link may send to
565 * the HCI without an ack coming back.
566 *
567 * Currently, this is a simple allocation, dividing the
568 * number of Controller Packets by the number of links. In
569 * the future, QOS configuration should be examined.
570 *
571 * Returns void
572 *
573 ******************************************************************************/
l2c_link_adjust_allocation(void)574 void l2c_link_adjust_allocation(void) {
575 uint16_t qq, yy, qq_remainder;
576 tL2C_LCB* p_lcb;
577 uint16_t hi_quota, low_quota;
578 uint16_t num_lowpri_links = 0;
579 uint16_t num_hipri_links = 0;
580 uint16_t controller_xmit_quota = l2cb.num_lm_acl_bufs;
581 uint16_t high_pri_link_quota = L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A;
582 bool is_share_buffer = (l2cb.num_lm_ble_bufs == L2C_DEF_NUM_BLE_BUF_SHARED) ? true : false;
583
584 /* If no links active, reset buffer quotas and controller buffers */
585 if (l2cb.num_used_lcbs == 0) {
586 l2cb.controller_xmit_window = l2cb.num_lm_acl_bufs;
587 l2cb.round_robin_quota = l2cb.round_robin_unacked = 0;
588 return;
589 }
590
591 /* First, count the links */
592 for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) {
593 if (p_lcb->in_use && (is_share_buffer || p_lcb->transport != BT_TRANSPORT_LE)) {
594 if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) {
595 num_hipri_links++;
596 } else {
597 num_lowpri_links++;
598 }
599 }
600 }
601
602 /* now adjust high priority link quota */
603 low_quota = num_lowpri_links ? 1 : 0;
604 while ((num_hipri_links * high_pri_link_quota + low_quota) > controller_xmit_quota) {
605 high_pri_link_quota--;
606 }
607
608 /* Work out the xmit quota and buffer quota high and low priorities */
609 hi_quota = num_hipri_links * high_pri_link_quota;
610 low_quota = (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1;
611
612 /* Work out and save the HCI xmit quota for each low priority link */
613
614 /* If each low priority link cannot have at least one buffer */
615 if (num_lowpri_links > low_quota) {
616 l2cb.round_robin_quota = low_quota;
617 qq = qq_remainder = 1;
618 } else if (num_lowpri_links > 0) {
619 /* If each low priority link can have at least one buffer */
620 l2cb.round_robin_quota = 0;
621 l2cb.round_robin_unacked = 0;
622 qq = low_quota / num_lowpri_links;
623 qq_remainder = low_quota % num_lowpri_links;
624 } else {
625 /* If no low priority link */
626 l2cb.round_robin_quota = 0;
627 l2cb.round_robin_unacked = 0;
628 qq = qq_remainder = 1;
629 }
630
631 log::debug(
632 "l2c_link_adjust_allocation num_hipri: {} num_lowpri: {} low_quota: "
633 "{} round_robin_quota: {} qq: {}",
634 num_hipri_links, num_lowpri_links, low_quota, l2cb.round_robin_quota, qq);
635
636 /* Now, assign the quotas to each link */
637 for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++) {
638 if (p_lcb->in_use && (is_share_buffer || p_lcb->transport != BT_TRANSPORT_LE)) {
639 if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) {
640 p_lcb->link_xmit_quota = high_pri_link_quota;
641 } else {
642 /* Safety check in case we switched to round-robin with something
643 * outstanding */
644 /* if sent_not_acked is added into round_robin_unacked then don't add it
645 * again */
646 /* l2cap keeps updating sent_not_acked for exiting from round robin */
647 if ((p_lcb->link_xmit_quota > 0) && (qq == 0)) {
648 l2cb.round_robin_unacked += p_lcb->sent_not_acked;
649 }
650
651 p_lcb->link_xmit_quota = qq;
652 if (qq_remainder > 0) {
653 p_lcb->link_xmit_quota++;
654 qq_remainder--;
655 }
656 }
657
658 log::debug("l2c_link_adjust_allocation LCB {} Priority: {} XmitQuota: {}", yy,
659 p_lcb->acl_priority, p_lcb->link_xmit_quota);
660
661 log::debug("SentNotAcked: {} RRUnacked: {}", p_lcb->sent_not_acked,
662 l2cb.round_robin_unacked);
663
664 /* There is a special case where we have readjusted the link quotas and */
665 /* this link may have sent anything but some other link sent packets so */
666 /* so we may need a timer to kick off this link's transmissions. */
667 if (p_lcb->link_xmit_data_q != nullptr) {
668 if ((p_lcb->link_state == LST_CONNECTED) &&
669 !list_is_empty(p_lcb->link_xmit_data_q) &&
670 (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) {
671 alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS,
672 l2c_lcb_timer_timeout, p_lcb);
673 }
674 } else {
675 log::warn("link_xmit_data_q is null");
676 }
677 }
678 }
679 }
680
681 /*******************************************************************************
682 *
683 * Function l2c_link_adjust_chnl_allocation
684 *
685 * Description This function is called to calculate the amount of packets
686 * each non-F&EC channel may have outstanding.
687 *
688 * Currently, this is a simple allocation, dividing the number
689 * of packets allocated to the link by the number of channels.
690 * In the future, QOS configuration should be examined.
691 *
692 * Returns void
693 *
694 ******************************************************************************/
l2c_link_adjust_chnl_allocation(void)695 void l2c_link_adjust_chnl_allocation(void) {
696 /* assign buffer quota to each channel based on its data rate requirement */
697 for (uint8_t xx = 0; xx < MAX_L2CAP_CHANNELS; xx++) {
698 tL2C_CCB* p_ccb = l2cb.ccb_pool + xx;
699
700 if (!p_ccb->in_use) {
701 continue;
702 }
703
704 tL2CAP_CHNL_DATA_RATE data_rate = p_ccb->tx_data_rate + p_ccb->rx_data_rate;
705 p_ccb->buff_quota = L2CAP_CBB_DEFAULT_DATA_RATE_BUFF_QUOTA * data_rate;
706 log::debug(
707 "CID:0x{:04x} FCR Mode:{} Priority:{} TxDataRate:{} RxDataRate:{} "
708 "Quota:{}",
709 p_ccb->local_cid, p_ccb->peer_cfg.fcr.mode, p_ccb->ccb_priority, p_ccb->tx_data_rate,
710 p_ccb->rx_data_rate, p_ccb->buff_quota);
711
712 /* quota may be change so check congestion */
713 l2cu_check_channel_congestion(p_ccb);
714 }
715 }
716
l2c_link_init(const uint16_t acl_buffer_count_classic)717 void l2c_link_init(const uint16_t acl_buffer_count_classic) {
718 l2cb.num_lm_acl_bufs = acl_buffer_count_classic;
719 l2cb.controller_xmit_window = acl_buffer_count_classic;
720 }
721
722 /*******************************************************************************
723 *
724 * Function l2c_link_role_changed
725 *
726 * Description This function is called whan a link's central/peripheral
727 *role change event is received. It simply updates the link control block.
728 *
729 * Returns void
730 *
731 ******************************************************************************/
l2c_link_role_changed(const RawAddress * bd_addr,tHCI_ROLE new_role,tHCI_STATUS hci_status)732 void l2c_link_role_changed(const RawAddress* bd_addr, tHCI_ROLE new_role, tHCI_STATUS hci_status) {
733 /* Make sure not called from HCI Command Status (bd_addr and new_role are
734 * invalid) */
735 if (bd_addr != nullptr) {
736 /* If here came form hci role change event */
737 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(*bd_addr, BT_TRANSPORT_BR_EDR);
738 if (p_lcb) {
739 if (new_role == HCI_ROLE_CENTRAL) {
740 p_lcb->SetLinkRoleAsCentral();
741 } else {
742 p_lcb->SetLinkRoleAsPeripheral();
743 }
744
745 /* Reset high priority link if needed */
746 if (hci_status == HCI_SUCCESS) {
747 l2cu_set_acl_priority(*bd_addr, p_lcb->acl_priority, true);
748 }
749 }
750 }
751
752 /* Check if any LCB was waiting for switch to be completed */
753 tL2C_LCB* p_lcb = &l2cb.lcb_pool[0];
754 for (uint8_t xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) {
755 if ((p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTING_WAIT_SWITCH)) {
756 l2cu_create_conn_after_switch(p_lcb);
757 }
758 }
759 }
760
761 /*******************************************************************************
762 *
763 * Function l2c_pin_code_request
764 *
765 * Description This function is called whan a pin-code request is received
766 * on a connection. If there are no channels active yet on the
767 * link, it extends the link first connection timer. Make sure
768 * that inactivity timer is not extended if PIN code happens
769 * to be after last ccb released.
770 *
771 * Returns void
772 *
773 ******************************************************************************/
l2c_pin_code_request(const RawAddress & bd_addr)774 void l2c_pin_code_request(const RawAddress& bd_addr) {
775 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
776
777 if ((p_lcb) && (!p_lcb->ccb_queue.p_first_ccb)) {
778 alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_CONNECT_EXT_TIMEOUT_MS,
779 l2c_lcb_timer_timeout, p_lcb);
780 }
781 }
782
783 /*******************************************************************************
784 *
785 * Function l2c_link_check_power_mode
786 *
787 * Description This function is called to check power mode.
788 *
789 * Returns true if link is going to be active from park
790 * false if nothing to send or not in park mode
791 *
792 ******************************************************************************/
l2c_link_check_power_mode(tL2C_LCB * p_lcb)793 static bool l2c_link_check_power_mode(tL2C_LCB* p_lcb) {
794 if (com::android::bluetooth::flags::transmit_smp_packets_before_release()) {
795 // TODO: Remove this function when flag transmit_smp_packets_before_release is released
796 return false;
797 }
798
799 bool need_to_active = false;
800
801 // Return false as LM modes are applicable for BREDR transport
802 if (p_lcb->is_transport_ble()) {
803 return false;
804 }
805 /*
806 * We only switch park to active only if we have unsent packets
807 */
808 if (list_is_empty(p_lcb->link_xmit_data_q)) {
809 for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) {
810 if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
811 need_to_active = true;
812 break;
813 }
814 }
815 } else {
816 need_to_active = true;
817 }
818
819 /* if we have packets to send */
820 if (need_to_active) {
821 /* check power mode */
822 tBTM_PM_MODE mode;
823 if (BTM_ReadPowerMode(p_lcb->remote_bd_addr, &mode)) {
824 if (mode == BTM_PM_STS_PENDING) {
825 log::debug("LCB(0x{:x}) is in PM pending state", p_lcb->Handle());
826 return true;
827 }
828 }
829 }
830 return false;
831 }
832
833 /*******************************************************************************
834 *
835 * Function l2c_link_check_send_pkts
836 *
837 * Description This function is called to check if it can send packets
838 * to the Host Controller. It may be passed the address of
839 * a packet to send.
840 *
841 * Returns void
842 *
843 ******************************************************************************/
l2c_link_check_send_pkts(tL2C_LCB * p_lcb,uint16_t local_cid,BT_HDR * p_buf)844 void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, BT_HDR* p_buf) {
845 bool single_write = false;
846
847 /* Save the channel ID for faster counting */
848 if (p_buf) {
849 p_buf->event = local_cid;
850 if (local_cid != 0) {
851 single_write = true;
852 }
853
854 p_buf->layer_specific = 0;
855 if (p_lcb->link_xmit_data_q != NULL) {
856 list_append(p_lcb->link_xmit_data_q, p_buf);
857 } else {
858 log::warn("Unable to queue packet as L2cap module transmit data queue is null");
859 }
860
861 if (p_lcb->link_xmit_quota == 0) {
862 if (p_lcb->transport == BT_TRANSPORT_LE) {
863 l2cb.ble_check_round_robin = true;
864 } else {
865 l2cb.check_round_robin = true;
866 }
867 }
868 }
869
870 /* If this is called from uncongested callback context break recursive
871 *calling.
872 ** This LCB will be served when receiving number of completed packet event.
873 */
874 if (l2cb.is_cong_cback_context) {
875 log::warn("skipping, is_cong_cback_context=true");
876 return;
877 }
878
879 /* If we are in a scenario where there are not enough buffers for each link to
880 ** have at least 1, then do a round-robin for all the LCBs
881 */
882 if ((p_lcb == NULL) || (p_lcb->link_xmit_quota == 0)) {
883 log::debug("Round robin");
884 if (p_lcb == NULL) {
885 p_lcb = l2cb.lcb_pool;
886 } else if (!single_write) {
887 p_lcb++;
888 }
889
890 /* Loop through, starting at the next */
891 for (int xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) {
892 /* Check for wraparound */
893 if (p_lcb == &l2cb.lcb_pool[MAX_L2CAP_LINKS]) {
894 p_lcb = &l2cb.lcb_pool[0];
895 }
896
897 /* If controller window is full, nothing to do */
898 if (((l2cb.controller_xmit_window == 0 ||
899 (l2cb.round_robin_unacked >= l2cb.round_robin_quota)) &&
900 (p_lcb->transport == BT_TRANSPORT_BR_EDR)) ||
901 (p_lcb->transport == BT_TRANSPORT_LE &&
902 (l2cb.ble_round_robin_unacked >= l2cb.ble_round_robin_quota ||
903 l2cb.controller_le_xmit_window == 0))) {
904 log::debug("Skipping lcb {} due to controller window full", xx);
905 continue;
906 }
907
908 if ((!p_lcb->in_use) || (p_lcb->link_state != LST_CONNECTED) ||
909 (p_lcb->link_xmit_quota != 0) || (l2c_link_check_power_mode(p_lcb))) {
910 log::debug("Skipping lcb {} due to quota", xx);
911 continue;
912 }
913
914 /* See if we can send anything from the Link Queue */
915 if (p_lcb->link_xmit_data_q != NULL && !list_is_empty(p_lcb->link_xmit_data_q)) {
916 log::verbose("Sending to lower layer");
917 p_buf = (BT_HDR*)list_front(p_lcb->link_xmit_data_q);
918 list_remove(p_lcb->link_xmit_data_q, p_buf);
919 l2c_link_send_to_lower(p_lcb, p_buf, NULL);
920 } else if (single_write) {
921 /* If only doing one write, break out */
922 log::debug("single_write is true, skipping");
923 break;
924 } else {
925 /* If nothing on the link queue, check the channel queue */
926 tL2C_TX_COMPLETE_CB_INFO cbi = {};
927 log::debug("Check next buffer");
928 p_buf = l2cu_get_next_buffer_to_send(p_lcb, &cbi);
929 if (p_buf != NULL) {
930 log::debug("Sending next buffer");
931 l2c_link_send_to_lower(p_lcb, p_buf, &cbi);
932 }
933 }
934 }
935
936 /* If we finished without using up our quota, no need for a safety check */
937 if ((l2cb.controller_xmit_window > 0) && (l2cb.round_robin_unacked < l2cb.round_robin_quota) &&
938 (p_lcb->transport == BT_TRANSPORT_BR_EDR)) {
939 l2cb.check_round_robin = false;
940 }
941
942 if ((l2cb.controller_le_xmit_window > 0) &&
943 (l2cb.ble_round_robin_unacked < l2cb.ble_round_robin_quota) &&
944 (p_lcb->transport == BT_TRANSPORT_LE)) {
945 l2cb.ble_check_round_robin = false;
946 }
947 } else /* if this is not round-robin service */
948 {
949 /* link_state or power mode not ready, can't send anything else */
950 if ((p_lcb->link_state != LST_CONNECTED) || (l2c_link_check_power_mode(p_lcb))) {
951 log::warn("Can't send, link state: {} not LST_CONNECTED or power mode BTM_PM_STS_PENDING",
952 p_lcb->link_state);
953 return;
954 }
955 log::verbose(
956 "Direct send, transport={}, xmit_window={}, le_xmit_window={}, "
957 "sent_not_acked={}, link_xmit_quota={}",
958 p_lcb->transport, l2cb.controller_xmit_window, l2cb.controller_le_xmit_window,
959 p_lcb->sent_not_acked, p_lcb->link_xmit_quota);
960
961 /* See if we can send anything from the link queue */
962 while (((l2cb.controller_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_BR_EDR)) ||
963 (l2cb.controller_le_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_LE))) &&
964 (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) {
965 if ((p_lcb->link_xmit_data_q == NULL) || list_is_empty(p_lcb->link_xmit_data_q)) {
966 log::verbose("No transmit data, skipping");
967 break;
968 }
969 log::verbose("Sending to lower layer");
970 p_buf = (BT_HDR*)list_front(p_lcb->link_xmit_data_q);
971 list_remove(p_lcb->link_xmit_data_q, p_buf);
972 l2c_link_send_to_lower(p_lcb, p_buf, NULL);
973 }
974
975 if (!single_write) {
976 /* See if we can send anything for any channel */
977 log::verbose("Trying to send other data when single_write is false");
978 while (((l2cb.controller_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_BR_EDR)) ||
979 (l2cb.controller_le_xmit_window != 0 && (p_lcb->transport == BT_TRANSPORT_LE))) &&
980 (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) {
981 tL2C_TX_COMPLETE_CB_INFO cbi = {};
982 p_buf = l2cu_get_next_buffer_to_send(p_lcb, &cbi);
983 if (p_buf == NULL) {
984 log::verbose("No next buffer, skipping");
985 break;
986 }
987 log::verbose("Sending to lower layer");
988 l2c_link_send_to_lower(p_lcb, p_buf, &cbi);
989 }
990 }
991
992 /* There is a special case where we have readjusted the link quotas and */
993 /* this link may have sent anything but some other link sent packets so */
994 /* so we may need a timer to kick off this link's transmissions. */
995 if ((p_lcb->link_xmit_data_q != NULL) && (!list_is_empty(p_lcb->link_xmit_data_q)) &&
996 (p_lcb->sent_not_acked < p_lcb->link_xmit_quota)) {
997 alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS,
998 l2c_lcb_timer_timeout, p_lcb);
999 }
1000 }
1001 }
1002
l2c_OnHciModeChangeSendPendingPackets(RawAddress remote)1003 void l2c_OnHciModeChangeSendPendingPackets(RawAddress remote) {
1004 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(remote, BT_TRANSPORT_BR_EDR);
1005 if (p_lcb != NULL) {
1006 /* There might be any pending packets due to SNIFF or PENDING state */
1007 /* Trigger L2C to start transmission of the pending packets. */
1008 log::verbose("btm mode change to active; check l2c_link for outgoing packets");
1009 l2c_link_check_send_pkts(p_lcb, 0, NULL);
1010 }
1011 }
1012
1013 /*******************************************************************************
1014 *
1015 * Function l2c_link_send_to_lower
1016 *
1017 * Description This function queues the buffer for HCI transmission
1018 *
1019 ******************************************************************************/
l2c_link_send_to_lower_br_edr(tL2C_LCB * p_lcb,BT_HDR * p_buf)1020 static void l2c_link_send_to_lower_br_edr(tL2C_LCB* p_lcb, BT_HDR* p_buf) {
1021 const uint16_t link_xmit_quota = p_lcb->link_xmit_quota;
1022
1023 if (link_xmit_quota == 0) {
1024 l2cb.round_robin_unacked++;
1025 }
1026 p_lcb->sent_not_acked++;
1027 p_buf->layer_specific = 0;
1028 l2cb.controller_xmit_window--;
1029
1030 acl_send_data_packet_br_edr(p_lcb->remote_bd_addr, p_buf);
1031 log::verbose("TotalWin={},Hndl=0x{:x},Quota={},Unack={},RRQuota={},RRUnack={}",
1032 l2cb.controller_xmit_window, p_lcb->Handle(), p_lcb->link_xmit_quota,
1033 p_lcb->sent_not_acked, l2cb.round_robin_quota, l2cb.round_robin_unacked);
1034 }
1035
l2c_link_send_to_lower_ble(tL2C_LCB * p_lcb,BT_HDR * p_buf)1036 static void l2c_link_send_to_lower_ble(tL2C_LCB* p_lcb, BT_HDR* p_buf) {
1037 const uint16_t link_xmit_quota = p_lcb->link_xmit_quota;
1038
1039 if (link_xmit_quota == 0) {
1040 l2cb.ble_round_robin_unacked++;
1041 }
1042 p_lcb->sent_not_acked++;
1043 p_buf->layer_specific = 0;
1044 l2cb.controller_le_xmit_window--;
1045
1046 acl_send_data_packet_ble(p_lcb->remote_bd_addr, p_buf);
1047 log::debug("TotalWin={},Hndl=0x{:x},Quota={},Unack={},RRQuota={},RRUnack={}",
1048 l2cb.controller_le_xmit_window, p_lcb->Handle(), p_lcb->link_xmit_quota,
1049 p_lcb->sent_not_acked, l2cb.ble_round_robin_quota, l2cb.ble_round_robin_unacked);
1050 }
1051
l2c_link_send_to_lower(tL2C_LCB * p_lcb,BT_HDR * p_buf,tL2C_TX_COMPLETE_CB_INFO * p_cbi)1052 static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf,
1053 tL2C_TX_COMPLETE_CB_INFO* p_cbi) {
1054 if (p_lcb->transport == BT_TRANSPORT_BR_EDR) {
1055 l2c_link_send_to_lower_br_edr(p_lcb, p_buf);
1056 } else {
1057 l2c_link_send_to_lower_ble(p_lcb, p_buf);
1058 }
1059 if (p_cbi) {
1060 l2cu_tx_complete(p_cbi);
1061 }
1062
1063 if (!com::android::bluetooth::flags::transmit_smp_packets_before_release() ||
1064 p_lcb->suspended.empty()) {
1065 return;
1066 }
1067
1068 auto it = p_lcb->suspended.begin();
1069 while (it != p_lcb->suspended.end()) {
1070 bool erase = false;
1071 uint16_t fixed_cid = *it;
1072
1073 if (fixed_cid < L2CAP_FIRST_FIXED_CHNL || fixed_cid > L2CAP_LAST_FIXED_CHNL) {
1074 log::warn("Unknown channel was marked for removal, CID: 0x{:04x} BDA: {}", fixed_cid,
1075 p_lcb->remote_bd_addr);
1076 erase = true;
1077 } else {
1078 auto p_ccb = p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL];
1079 if (p_ccb == nullptr || !p_ccb->in_use) {
1080 log::warn(
1081 "Fixed channel control block not active but was marked for removal, CID: 0x{:04x} "
1082 "BDA: {}",
1083 fixed_cid, p_lcb->remote_bd_addr);
1084 erase = true;
1085 } else if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1086 if (L2CA_RemoveFixedChnl(fixed_cid, p_lcb->remote_bd_addr)) {
1087 log::info("Finally removed CID: 0x{:04x} BDA: {}", fixed_cid, p_lcb->remote_bd_addr);
1088 } else {
1089 log::error("Failed to remove CID: 0x{:04x} BDA: {}", fixed_cid, p_lcb->remote_bd_addr);
1090 }
1091 erase = true;
1092 }
1093 }
1094
1095 if (erase) {
1096 it = p_lcb->suspended.erase(it);
1097 } else {
1098 it++;
1099 }
1100 }
1101 }
1102
l2c_packets_completed(uint16_t handle,uint16_t num_sent)1103 void l2c_packets_completed(uint16_t handle, uint16_t num_sent) {
1104 tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
1105 if (p_lcb == nullptr) {
1106 return;
1107 }
1108 p_lcb->update_outstanding_packets(num_sent);
1109
1110 switch (p_lcb->transport) {
1111 case BT_TRANSPORT_BR_EDR:
1112 l2cb.controller_xmit_window += num_sent;
1113 if (p_lcb->is_round_robin_scheduling()) {
1114 l2cb.update_outstanding_classic_packets(num_sent);
1115 }
1116 break;
1117 case BT_TRANSPORT_LE:
1118 l2cb.controller_le_xmit_window += num_sent;
1119 if (p_lcb->is_round_robin_scheduling()) {
1120 l2cb.update_outstanding_le_packets(num_sent);
1121 }
1122 break;
1123 default:
1124 log::error("Unknown transport received:{}", p_lcb->transport);
1125 return;
1126 }
1127
1128 l2c_link_check_send_pkts(p_lcb, 0, NULL);
1129
1130 if (p_lcb->is_high_priority()) {
1131 switch (p_lcb->transport) {
1132 case BT_TRANSPORT_LE:
1133 if (l2cb.ble_check_round_robin && l2cb.is_ble_round_robin_quota_available()) {
1134 l2c_link_check_send_pkts(NULL, 0, NULL);
1135 }
1136 break;
1137 case BT_TRANSPORT_BR_EDR:
1138 if (l2cb.check_round_robin && l2cb.is_classic_round_robin_quota_available()) {
1139 l2c_link_check_send_pkts(NULL, 0, NULL);
1140 }
1141 break;
1142 default:
1143 break;
1144 }
1145 }
1146 }
1147
l2cu_ConnectAclForSecurity(const RawAddress & bd_addr)1148 tBTM_STATUS l2cu_ConnectAclForSecurity(const RawAddress& bd_addr) {
1149 tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
1150 if (p_lcb && (p_lcb->link_state == LST_CONNECTED || p_lcb->link_state == LST_CONNECTING)) {
1151 log::warn("Connection already exists");
1152 return tBTM_STATUS::BTM_CMD_STARTED;
1153 }
1154
1155 /* Make sure an L2cap link control block is available */
1156 if (!p_lcb && (p_lcb = l2cu_allocate_lcb(bd_addr, true, BT_TRANSPORT_BR_EDR)) == NULL) {
1157 log::warn("failed allocate LCB for {}", bd_addr);
1158 return tBTM_STATUS::BTM_NO_RESOURCES;
1159 }
1160
1161 l2cu_create_conn_br_edr(p_lcb);
1162 return tBTM_STATUS::BTM_SUCCESS;
1163 }
1164
l2cble_update_sec_act(const RawAddress & bd_addr,uint16_t sec_act)1165 void l2cble_update_sec_act(const RawAddress& bd_addr, uint16_t sec_act) {
1166 tL2C_LCB* lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
1167 lcb->sec_act = sec_act;
1168 }
1169
1170 /******************************************************************************
1171 *
1172 * Function l2cu_get_next_channel_in_rr
1173 *
1174 * Description get the next channel to send on a link. It also adjusts the
1175 * CCB queue to do a basic priority and round-robin scheduling.
1176 *
1177 * Returns pointer to CCB or NULL
1178 *
1179 ******************************************************************************/
l2cu_get_next_channel_in_rr(tL2C_LCB * p_lcb)1180 static tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb) {
1181 tL2C_CCB* p_serve_ccb = NULL;
1182 tL2C_CCB* p_ccb;
1183
1184 int i, j;
1185
1186 /* scan all of priority until finding a channel to serve */
1187 for (i = 0; (i < L2CAP_NUM_CHNL_PRIORITY) && (!p_serve_ccb); i++) {
1188 /* scan all channel within serving priority group until finding a channel to
1189 * serve */
1190 for (j = 0; (j < p_lcb->rr_serv[p_lcb->rr_pri].num_ccb) && (!p_serve_ccb); j++) {
1191 /* scaning from next serving channel */
1192 p_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb;
1193
1194 if (!p_ccb) {
1195 log::error("p_serve_ccb is NULL, rr_pri={}", p_lcb->rr_pri);
1196 return NULL;
1197 }
1198
1199 /* store the next serving channel */
1200 /* this channel is the last channel of its priority group */
1201 if ((p_ccb->p_next_ccb == NULL) || (p_ccb->p_next_ccb->ccb_priority != p_ccb->ccb_priority)) {
1202 /* next serving channel is set to the first channel in the group */
1203 p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_first_ccb;
1204 } else {
1205 /* next serving channel is set to the next channel in the group */
1206 p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = p_ccb->p_next_ccb;
1207 }
1208
1209 if (p_ccb->chnl_state != CST_OPEN) {
1210 continue;
1211 }
1212
1213 if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
1214 log::debug("Connection oriented channel");
1215 if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1216 continue;
1217 }
1218
1219 } else {
1220 /* eL2CAP option in use */
1221 if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) {
1222 if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) {
1223 continue;
1224 }
1225
1226 if (fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) {
1227 if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1228 continue;
1229 }
1230
1231 /* If in eRTM mode, check for window closure */
1232 if ((p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) &&
1233 (l2c_fcr_is_flow_controlled(p_ccb))) {
1234 continue;
1235 }
1236 }
1237 } else {
1238 if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1239 continue;
1240 }
1241 }
1242 }
1243
1244 /* found a channel to serve */
1245 p_serve_ccb = p_ccb;
1246 /* decrease quota of its priority group */
1247 p_lcb->rr_serv[p_lcb->rr_pri].quota--;
1248 }
1249
1250 /* if there is no more quota of the priority group or no channel to have
1251 * data to send */
1252 if ((p_lcb->rr_serv[p_lcb->rr_pri].quota == 0) || (!p_serve_ccb)) {
1253 /* serve next priority group */
1254 p_lcb->rr_pri = (p_lcb->rr_pri + 1) % L2CAP_NUM_CHNL_PRIORITY;
1255 /* initialize its quota */
1256 p_lcb->rr_serv[p_lcb->rr_pri].quota = L2CAP_GET_PRIORITY_QUOTA(p_lcb->rr_pri);
1257 }
1258 }
1259
1260 if (p_serve_ccb) {
1261 log::verbose("RR service pri={}, quota={}, lcid=0x{:04x}", p_serve_ccb->ccb_priority,
1262 p_lcb->rr_serv[p_serve_ccb->ccb_priority].quota, p_serve_ccb->local_cid);
1263 }
1264
1265 return p_serve_ccb;
1266 }
1267
1268 /******************************************************************************
1269 *
1270 * Function l2cu_get_next_buffer_to_send
1271 *
1272 * Description get the next buffer to send on a link. It also adjusts the
1273 * CCB queue to do a basic priority and round-robin scheduling.
1274 *
1275 * Returns pointer to buffer or NULL
1276 *
1277 ******************************************************************************/
l2cu_get_next_buffer_to_send(tL2C_LCB * p_lcb,tL2C_TX_COMPLETE_CB_INFO * p_cbi)1278 static BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb, tL2C_TX_COMPLETE_CB_INFO* p_cbi) {
1279 tL2C_CCB* p_ccb;
1280 BT_HDR* p_buf;
1281
1282 /* Highest priority are fixed channels */
1283 int xx;
1284
1285 p_cbi->cb = NULL;
1286
1287 for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) {
1288 p_ccb = p_lcb->p_fixed_ccbs[xx];
1289 if (p_ccb == NULL) {
1290 continue;
1291 }
1292
1293 /* eL2CAP option in use */
1294 if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) {
1295 if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) {
1296 continue;
1297 }
1298
1299 /* No more checks needed if sending from the reatransmit queue */
1300 if (fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) {
1301 if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1302 continue;
1303 }
1304
1305 /* If in eRTM mode, check for window closure */
1306 if ((p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) &&
1307 (l2c_fcr_is_flow_controlled(p_ccb))) {
1308 continue;
1309 }
1310 }
1311
1312 p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0);
1313 if (p_buf != NULL) {
1314 l2cu_check_channel_congestion(p_ccb);
1315 l2cu_set_acl_hci_header(p_buf, p_ccb);
1316 return p_buf;
1317 }
1318 } else {
1319 if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1320 p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1321 if (NULL == p_buf) {
1322 log::error("No data to be sent");
1323 return NULL;
1324 }
1325
1326 /* Prepare callback info for TX completion */
1327 p_cbi->cb = l2cb.fixed_reg[xx].pL2CA_FixedTxComplete_Cb;
1328 p_cbi->local_cid = p_ccb->local_cid;
1329 p_cbi->num_sdu = 1;
1330
1331 l2cu_check_channel_congestion(p_ccb);
1332 l2cu_set_acl_hci_header(p_buf, p_ccb);
1333 return p_buf;
1334 }
1335 }
1336 }
1337
1338 /* get next serving channel in round-robin */
1339 p_ccb = l2cu_get_next_channel_in_rr(p_lcb);
1340
1341 /* Return if no buffer */
1342 if (p_ccb == NULL) {
1343 return NULL;
1344 }
1345
1346 if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
1347 /* Check credits */
1348 if (p_ccb->peer_conn_cfg.credits == 0) {
1349 log::debug("No credits to send packets");
1350 return NULL;
1351 }
1352
1353 bool last_piece_of_sdu = false;
1354 p_buf = l2c_lcc_get_next_xmit_sdu_seg(p_ccb, &last_piece_of_sdu);
1355 p_ccb->peer_conn_cfg.credits--;
1356
1357 if (last_piece_of_sdu) {
1358 // TODO: send callback up the stack. Investigate setting p_cbi->cb to
1359 // notify after controller ack send.
1360 }
1361
1362 } else {
1363 if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) {
1364 p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0);
1365 if (p_buf == NULL) {
1366 return NULL;
1367 }
1368 } else {
1369 p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1370 if (NULL == p_buf) {
1371 log::error("#2: No data to be sent");
1372 return NULL;
1373 }
1374 }
1375 }
1376
1377 if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_TxComplete_Cb &&
1378 (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE)) {
1379 (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, 1);
1380 }
1381
1382 l2cu_check_channel_congestion(p_ccb);
1383
1384 l2cu_set_acl_hci_header(p_buf, p_ccb);
1385
1386 return p_buf;
1387 }
1388