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