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 acl_data_size_classic =
1051       controller_get_interface()->get_acl_data_size_classic();
1052   const uint16_t link_xmit_quota = p_lcb->link_xmit_quota;
1053   const bool is_bdr_and_fits_in_buffer =
1054       bluetooth::shim::is_gd_acl_enabled()
1055           ? true
1056           : (p_buf->len <= acl_packet_size_classic);
1057 
1058   if (is_bdr_and_fits_in_buffer) {
1059     if (link_xmit_quota == 0) {
1060       l2cb.round_robin_unacked++;
1061     }
1062     p_lcb->sent_not_acked++;
1063     p_buf->layer_specific = 0;
1064     l2cb.controller_xmit_window--;
1065   } else {
1066     uint16_t num_segs =
1067         (p_buf->len - HCI_DATA_PREAMBLE_SIZE + acl_data_size_classic - 1) /
1068         acl_data_size_classic;
1069 
1070     /* If doing round-robin, then only 1 segment each time */
1071     if (p_lcb->link_xmit_quota == 0) {
1072       num_segs = 1;
1073       p_lcb->partial_segment_being_sent = true;
1074     } else {
1075       /* Multi-segment packet. Make sure it can fit */
1076       if (num_segs > l2cb.controller_xmit_window) {
1077         num_segs = l2cb.controller_xmit_window;
1078         p_lcb->partial_segment_being_sent = true;
1079       }
1080 
1081       if (num_segs > (p_lcb->link_xmit_quota - p_lcb->sent_not_acked)) {
1082         num_segs = (p_lcb->link_xmit_quota - p_lcb->sent_not_acked);
1083         p_lcb->partial_segment_being_sent = true;
1084       }
1085     }
1086 
1087     p_lcb->sent_not_acked += num_segs;
1088     p_buf->layer_specific = num_segs;
1089     l2cb.controller_xmit_window -= num_segs;
1090     if (p_lcb->link_xmit_quota == 0) l2cb.round_robin_unacked += num_segs;
1091   }
1092   acl_send_data_packet_br_edr(p_lcb->remote_bd_addr, p_buf);
1093   LOG_DEBUG("TotalWin=%d,Hndl=0x%x,Quota=%d,Unack=%d,RRQuota=%d,RRUnack=%d",
1094             l2cb.controller_xmit_window, p_lcb->Handle(),
1095             p_lcb->link_xmit_quota, p_lcb->sent_not_acked,
1096             l2cb.round_robin_quota, l2cb.round_robin_unacked);
1097 }
1098 
l2c_link_send_to_lower_ble(tL2C_LCB * p_lcb,BT_HDR * p_buf)1099 static void l2c_link_send_to_lower_ble(tL2C_LCB* p_lcb, BT_HDR* p_buf) {
1100   const uint16_t acl_packet_size_ble =
1101       controller_get_interface()->get_acl_packet_size_ble();
1102   const uint16_t acl_data_size_ble =
1103       controller_get_interface()->get_acl_data_size_ble();
1104   const uint16_t link_xmit_quota = p_lcb->link_xmit_quota;
1105   const bool is_ble_and_fits_in_buffer = (p_buf->len <= acl_packet_size_ble);
1106 
1107   if (is_ble_and_fits_in_buffer) {
1108     if (link_xmit_quota == 0) {
1109       l2cb.ble_round_robin_unacked++;
1110     }
1111     p_lcb->sent_not_acked++;
1112     p_buf->layer_specific = 0;
1113     l2cb.controller_le_xmit_window--;
1114   } else {
1115     uint16_t num_segs =
1116         (p_buf->len - HCI_DATA_PREAMBLE_SIZE + acl_data_size_ble - 1) /
1117         acl_data_size_ble;
1118 
1119     /* If doing round-robin, then only 1 segment each time */
1120     if (p_lcb->link_xmit_quota == 0) {
1121       num_segs = 1;
1122       p_lcb->partial_segment_being_sent = true;
1123     } else {
1124       /* Multi-segment packet. Make sure it can fit */
1125       if (num_segs > l2cb.controller_le_xmit_window) {
1126         num_segs = l2cb.controller_le_xmit_window;
1127         p_lcb->partial_segment_being_sent = true;
1128       }
1129 
1130       if (num_segs > (p_lcb->link_xmit_quota - p_lcb->sent_not_acked)) {
1131         num_segs = (p_lcb->link_xmit_quota - p_lcb->sent_not_acked);
1132         p_lcb->partial_segment_being_sent = true;
1133       }
1134     }
1135 
1136     p_lcb->sent_not_acked += num_segs;
1137     p_buf->layer_specific = num_segs;
1138     l2cb.controller_le_xmit_window -= num_segs;
1139     if (p_lcb->link_xmit_quota == 0) l2cb.ble_round_robin_unacked += num_segs;
1140   }
1141   acl_send_data_packet_ble(p_lcb->remote_bd_addr, p_buf);
1142   LOG_DEBUG("TotalWin=%d,Hndl=0x%x,Quota=%d,Unack=%d,RRQuota=%d,RRUnack=%d",
1143             l2cb.controller_le_xmit_window, p_lcb->Handle(),
1144             p_lcb->link_xmit_quota, p_lcb->sent_not_acked,
1145             l2cb.ble_round_robin_quota, l2cb.ble_round_robin_unacked);
1146 }
1147 
l2c_link_send_to_lower(tL2C_LCB * p_lcb,BT_HDR * p_buf)1148 static void l2c_link_send_to_lower(tL2C_LCB* p_lcb, BT_HDR* p_buf) {
1149   if (p_lcb->transport == BT_TRANSPORT_BR_EDR) {
1150     l2c_link_send_to_lower_br_edr(p_lcb, p_buf);
1151   } else {
1152     l2c_link_send_to_lower_ble(p_lcb, p_buf);
1153   }
1154 }
1155 
1156 /*******************************************************************************
1157  *
1158  * Function         l2c_link_process_num_completed_pkts
1159  *
1160  * Description      This function is called when a "number-of-completed-packets"
1161  *                  event is received from the controller. It updates all the
1162  *                  LCB transmit counts.
1163  *
1164  * Returns          void
1165  *
1166  ******************************************************************************/
l2c_link_process_num_completed_pkts(uint8_t * p,uint8_t evt_len)1167 void l2c_link_process_num_completed_pkts(uint8_t* p, uint8_t evt_len) {
1168   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1169     return;
1170   }
1171   uint8_t num_handles, xx;
1172   uint16_t handle;
1173   uint16_t num_sent;
1174   tL2C_LCB* p_lcb;
1175 
1176   if (evt_len > 0) {
1177     STREAM_TO_UINT8(num_handles, p);
1178   } else {
1179     num_handles = 0;
1180   }
1181 
1182   if (num_handles > evt_len / (2 * sizeof(uint16_t))) {
1183     android_errorWriteLog(0x534e4554, "141617601");
1184     num_handles = evt_len / (2 * sizeof(uint16_t));
1185   }
1186 
1187   for (xx = 0; xx < num_handles; xx++) {
1188     STREAM_TO_UINT16(handle, p);
1189     /* Extract the handle */
1190     handle = HCID_GET_HANDLE(handle);
1191     STREAM_TO_UINT16(num_sent, p);
1192 
1193     p_lcb = l2cu_find_lcb_by_handle(handle);
1194 
1195     if (p_lcb) {
1196       if (p_lcb && (p_lcb->transport == BT_TRANSPORT_LE))
1197         l2cb.controller_le_xmit_window += num_sent;
1198       else {
1199         /* Maintain the total window to the controller */
1200         l2cb.controller_xmit_window += num_sent;
1201       }
1202       /* If doing round-robin, adjust communal counts */
1203       if (p_lcb->link_xmit_quota == 0) {
1204         if (p_lcb->transport == BT_TRANSPORT_LE) {
1205           /* Don't go negative */
1206           if (l2cb.ble_round_robin_unacked > num_sent)
1207             l2cb.ble_round_robin_unacked -= num_sent;
1208           else
1209             l2cb.ble_round_robin_unacked = 0;
1210         } else {
1211           /* Don't go negative */
1212           if (l2cb.round_robin_unacked > num_sent)
1213             l2cb.round_robin_unacked -= num_sent;
1214           else
1215             l2cb.round_robin_unacked = 0;
1216         }
1217       }
1218 
1219       /* Don't go negative */
1220       if (p_lcb->sent_not_acked > num_sent)
1221         p_lcb->sent_not_acked -= num_sent;
1222       else
1223         p_lcb->sent_not_acked = 0;
1224 
1225       l2c_link_check_send_pkts(p_lcb, 0, NULL);
1226 
1227       /* If we were doing round-robin for low priority links, check 'em */
1228       if ((p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) &&
1229           (l2cb.check_round_robin) &&
1230           (l2cb.round_robin_unacked < l2cb.round_robin_quota)) {
1231         l2c_link_check_send_pkts(NULL, 0, NULL);
1232       }
1233       if ((p_lcb->transport == BT_TRANSPORT_LE) &&
1234           (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH) &&
1235           ((l2cb.ble_check_round_robin) &&
1236            (l2cb.ble_round_robin_unacked < l2cb.ble_round_robin_quota))) {
1237         l2c_link_check_send_pkts(NULL, 0, NULL);
1238       }
1239     }
1240 
1241     if (p_lcb) {
1242       if (p_lcb->transport == BT_TRANSPORT_LE) {
1243         LOG_DEBUG("TotalWin=%d,LinkUnack(0x%x)=%d,RRCheck=%d,RRUnack=%d",
1244                   l2cb.controller_le_xmit_window, p_lcb->Handle(),
1245                   p_lcb->sent_not_acked, l2cb.ble_check_round_robin,
1246                   l2cb.ble_round_robin_unacked);
1247       } else {
1248         LOG_DEBUG("TotalWin=%d,LinkUnack(0x%x)=%d,RRCheck=%d,RRUnack=%d",
1249                   l2cb.controller_xmit_window, p_lcb->Handle(),
1250                   p_lcb->sent_not_acked, l2cb.check_round_robin,
1251                   l2cb.round_robin_unacked);
1252       }
1253     } else {
1254       LOG_DEBUG("TotalWin=%d  LE_Win: %d, Handle=0x%x, RRCheck=%d, RRUnack=%d",
1255                 l2cb.controller_xmit_window, l2cb.controller_le_xmit_window,
1256                 handle, l2cb.ble_check_round_robin,
1257                 l2cb.ble_round_robin_unacked);
1258     }
1259   }
1260 }
1261 
l2c_packets_completed(uint16_t handle,uint16_t num_sent)1262 void l2c_packets_completed(uint16_t handle, uint16_t num_sent) {
1263   tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
1264   if (p_lcb == nullptr) {
1265     LOG_WARN("Received l2c packets completed for unknown ACL");
1266     return;
1267   }
1268   p_lcb->update_outstanding_packets(num_sent);
1269 
1270   switch (p_lcb->transport) {
1271     case BT_TRANSPORT_BR_EDR:
1272       l2cb.controller_xmit_window += num_sent;
1273       if (p_lcb->is_round_robin_scheduling())
1274         l2cb.update_outstanding_classic_packets(num_sent);
1275       break;
1276     case BT_TRANSPORT_LE:
1277       l2cb.controller_le_xmit_window += num_sent;
1278       if (p_lcb->is_round_robin_scheduling())
1279         l2cb.update_outstanding_le_packets(num_sent);
1280       break;
1281     default:
1282       LOG_ERROR("Unknown transport received:%u", p_lcb->transport);
1283       return;
1284   }
1285 
1286   l2c_link_check_send_pkts(p_lcb, 0, NULL);
1287 
1288   if (p_lcb->is_high_priority()) {
1289     switch (p_lcb->transport) {
1290       case BT_TRANSPORT_LE:
1291         if (l2cb.ble_check_round_robin &&
1292             l2cb.is_ble_round_robin_quota_available())
1293           l2c_link_check_send_pkts(NULL, 0, NULL);
1294         break;
1295       case BT_TRANSPORT_BR_EDR:
1296         if (l2cb.check_round_robin &&
1297             l2cb.is_classic_round_robin_quota_available()) {
1298           l2c_link_check_send_pkts(NULL, 0, NULL);
1299         }
1300         break;
1301       default:
1302         break;
1303     }
1304   }
1305 }
1306 
1307 /*******************************************************************************
1308  *
1309  * Function         l2c_link_segments_xmitted
1310  *
1311  * Description      This function is called from the HCI Interface when an ACL
1312  *                  data packet segment is transmitted.
1313  *
1314  * Returns          void
1315  *
1316  ******************************************************************************/
l2c_link_segments_xmitted(BT_HDR * p_msg)1317 void l2c_link_segments_xmitted(BT_HDR* p_msg) {
1318   uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset;
1319 
1320   /* Extract the handle */
1321   uint16_t handle{HCI_INVALID_HANDLE};
1322   STREAM_TO_UINT16(handle, p);
1323   handle = HCID_GET_HANDLE(handle);
1324 
1325   /* Find the LCB based on the handle */
1326   tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
1327   if (p_lcb == nullptr) {
1328     LOG_WARN("Received segment complete for unknown connection handle:%d",
1329              handle);
1330     osi_free(p_msg);
1331     return;
1332   }
1333 
1334   if (p_lcb->link_state != LST_CONNECTED) {
1335     LOG_INFO("Received segment complete for unconnected connection handle:%d:",
1336              handle);
1337     osi_free(p_msg);
1338     return;
1339   }
1340 
1341   /* Enqueue the buffer to the head of the transmit queue, and see */
1342   /* if we can transmit anything more.                             */
1343   list_prepend(p_lcb->link_xmit_data_q, p_msg);
1344 
1345   p_lcb->partial_segment_being_sent = false;
1346 
1347   l2c_link_check_send_pkts(p_lcb, 0, NULL);
1348 }
1349 
l2cu_ConnectAclForSecurity(const RawAddress & bd_addr)1350 tBTM_STATUS l2cu_ConnectAclForSecurity(const RawAddress& bd_addr) {
1351   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1352     bluetooth::shim::L2CA_ConnectForSecurity(bd_addr);
1353     return BTM_SUCCESS;
1354   }
1355 
1356   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
1357   if (p_lcb && (p_lcb->link_state == LST_CONNECTED ||
1358                 p_lcb->link_state == LST_CONNECTING)) {
1359     LOG_WARN("Connection already exists");
1360     return BTM_CMD_STARTED;
1361   }
1362 
1363   /* Make sure an L2cap link control block is available */
1364   if (!p_lcb &&
1365       (p_lcb = l2cu_allocate_lcb(bd_addr, true, BT_TRANSPORT_BR_EDR)) == NULL) {
1366     LOG_WARN("failed allocate LCB for %s", bd_addr.ToString().c_str());
1367     return BTM_NO_RESOURCES;
1368   }
1369 
1370   l2cu_create_conn_br_edr(p_lcb);
1371   btm_acl_set_paging(true);
1372   return BTM_SUCCESS;
1373 }
1374 
l2cble_update_sec_act(const RawAddress & bd_addr,uint16_t sec_act)1375 void l2cble_update_sec_act(const RawAddress& bd_addr, uint16_t sec_act) {
1376   tL2C_LCB* lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
1377   lcb->sec_act = sec_act;
1378 }
1379 
1380 /******************************************************************************
1381  *
1382  * Function         l2cu_get_next_channel_in_rr
1383  *
1384  * Description      get the next channel to send on a link. It also adjusts the
1385  *                  CCB queue to do a basic priority and round-robin scheduling.
1386  *
1387  * Returns          pointer to CCB or NULL
1388  *
1389  ******************************************************************************/
l2cu_get_next_channel_in_rr(tL2C_LCB * p_lcb)1390 tL2C_CCB* l2cu_get_next_channel_in_rr(tL2C_LCB* p_lcb) {
1391   tL2C_CCB* p_serve_ccb = NULL;
1392   tL2C_CCB* p_ccb;
1393 
1394   int i, j;
1395 
1396   /* scan all of priority until finding a channel to serve */
1397   for (i = 0; (i < L2CAP_NUM_CHNL_PRIORITY) && (!p_serve_ccb); i++) {
1398     /* scan all channel within serving priority group until finding a channel to
1399      * serve */
1400     for (j = 0; (j < p_lcb->rr_serv[p_lcb->rr_pri].num_ccb) && (!p_serve_ccb);
1401          j++) {
1402       /* scaning from next serving channel */
1403       p_ccb = p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb;
1404 
1405       if (!p_ccb) {
1406         LOG_ERROR("p_serve_ccb is NULL, rr_pri=%d", p_lcb->rr_pri);
1407         return NULL;
1408       }
1409 
1410       LOG_DEBUG("RR scan pri=%d, lcid=0x%04x, q_cout=%zu", p_ccb->ccb_priority,
1411                 p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q));
1412 
1413       /* store the next serving channel */
1414       /* this channel is the last channel of its priority group */
1415       if ((p_ccb->p_next_ccb == NULL) ||
1416           (p_ccb->p_next_ccb->ccb_priority != p_ccb->ccb_priority)) {
1417         /* next serving channel is set to the first channel in the group */
1418         p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb =
1419             p_lcb->rr_serv[p_lcb->rr_pri].p_first_ccb;
1420       } else {
1421         /* next serving channel is set to the next channel in the group */
1422         p_lcb->rr_serv[p_lcb->rr_pri].p_serve_ccb = p_ccb->p_next_ccb;
1423       }
1424 
1425       if (p_ccb->chnl_state != CST_OPEN) continue;
1426 
1427       if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
1428         LOG_DEBUG("Connection oriented channel");
1429         if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue;
1430 
1431       } else {
1432         /* eL2CAP option in use */
1433         if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) {
1434           if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) continue;
1435 
1436           if (fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) {
1437             if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue;
1438 
1439             /* If in eRTM mode, check for window closure */
1440             if ((p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) &&
1441                 (l2c_fcr_is_flow_controlled(p_ccb)))
1442               continue;
1443           }
1444         } else {
1445           if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue;
1446         }
1447       }
1448 
1449       /* found a channel to serve */
1450       p_serve_ccb = p_ccb;
1451       /* decrease quota of its priority group */
1452       p_lcb->rr_serv[p_lcb->rr_pri].quota--;
1453     }
1454 
1455     /* if there is no more quota of the priority group or no channel to have
1456      * data to send */
1457     if ((p_lcb->rr_serv[p_lcb->rr_pri].quota == 0) || (!p_serve_ccb)) {
1458       /* serve next priority group */
1459       p_lcb->rr_pri = (p_lcb->rr_pri + 1) % L2CAP_NUM_CHNL_PRIORITY;
1460       /* initialize its quota */
1461       p_lcb->rr_serv[p_lcb->rr_pri].quota =
1462           L2CAP_GET_PRIORITY_QUOTA(p_lcb->rr_pri);
1463     }
1464   }
1465 
1466   if (p_serve_ccb) {
1467     LOG_DEBUG("RR service pri=%d, quota=%d, lcid=0x%04x",
1468               p_serve_ccb->ccb_priority,
1469               p_lcb->rr_serv[p_serve_ccb->ccb_priority].quota,
1470               p_serve_ccb->local_cid);
1471   }
1472 
1473   return p_serve_ccb;
1474 }
1475 
1476 /******************************************************************************
1477  *
1478  * Function         l2cu_get_next_buffer_to_send
1479  *
1480  * Description      get the next buffer to send on a link. It also adjusts the
1481  *                  CCB queue to do a basic priority and round-robin scheduling.
1482  *
1483  * Returns          pointer to buffer or NULL
1484  *
1485  ******************************************************************************/
l2cu_get_next_buffer_to_send(tL2C_LCB * p_lcb)1486 BT_HDR* l2cu_get_next_buffer_to_send(tL2C_LCB* p_lcb) {
1487   tL2C_CCB* p_ccb;
1488   BT_HDR* p_buf;
1489 
1490   /* Highest priority are fixed channels */
1491   int xx;
1492 
1493   for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) {
1494     p_ccb = p_lcb->p_fixed_ccbs[xx];
1495     if (p_ccb == NULL) continue;
1496 
1497     /* eL2CAP option in use */
1498     if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) {
1499       if (p_ccb->fcrb.wait_ack || p_ccb->fcrb.remote_busy) continue;
1500 
1501       /* No more checks needed if sending from the reatransmit queue */
1502       if (fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) {
1503         if (fixed_queue_is_empty(p_ccb->xmit_hold_q)) continue;
1504 
1505         /* If in eRTM mode, check for window closure */
1506         if ((p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) &&
1507             (l2c_fcr_is_flow_controlled(p_ccb)))
1508           continue;
1509       }
1510 
1511       p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0);
1512       if (p_buf != NULL) {
1513         l2cu_check_channel_congestion(p_ccb);
1514         l2cu_set_acl_hci_header(p_buf, p_ccb);
1515         return (p_buf);
1516       }
1517     } else {
1518       if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1519         p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1520         if (NULL == p_buf) {
1521           LOG_ERROR("No data to be sent");
1522           return (NULL);
1523         }
1524 
1525         l2cu_check_channel_congestion(p_ccb);
1526         l2cu_set_acl_hci_header(p_buf, p_ccb);
1527         return (p_buf);
1528       }
1529     }
1530   }
1531 
1532   /* get next serving channel in round-robin */
1533   p_ccb = l2cu_get_next_channel_in_rr(p_lcb);
1534 
1535   /* Return if no buffer */
1536   if (p_ccb == NULL) return (NULL);
1537 
1538   if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
1539     /* Check credits */
1540     if (p_ccb->peer_conn_cfg.credits == 0) {
1541       LOG_DEBUG("No credits to send packets");
1542       return NULL;
1543     }
1544 
1545     bool last_piece_of_sdu = false;
1546     p_buf = l2c_lcc_get_next_xmit_sdu_seg(p_ccb, &last_piece_of_sdu);
1547     p_ccb->peer_conn_cfg.credits--;
1548 
1549     if (last_piece_of_sdu) {
1550       // TODO: send callback up the stack. Investigate setting p_cbi->cb to
1551       // notify after controller ack send.
1552     }
1553 
1554   } else {
1555     if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) {
1556       p_buf = l2c_fcr_get_next_xmit_sdu_seg(p_ccb, 0);
1557       if (p_buf == NULL) return (NULL);
1558     } else {
1559       p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1560       if (NULL == p_buf) {
1561         LOG_ERROR("#2: No data to be sent");
1562         return (NULL);
1563       }
1564     }
1565   }
1566 
1567   if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_TxComplete_Cb &&
1568       (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE))
1569     (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, 1);
1570 
1571   l2cu_check_channel_congestion(p_ccb);
1572 
1573   l2cu_set_acl_hci_header(p_buf, p_ccb);
1574 
1575   return (p_buf);
1576 }
1577