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