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