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