Home | History | Annotate | Download | only in l2cap
      1 /******************************************************************************
      2  *
      3  *  Copyright 1999-2012 Broadcom Corporation
      4  *
      5  *  Licensed under the Apache License, Version 2.0 (the "License");
      6  *  you may not use this file except in compliance with the License.
      7  *  You may obtain a copy of the License at:
      8  *
      9  *  http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  *
     17  ******************************************************************************/
     18 
     19 /******************************************************************************
     20  *
     21  *  This file contains the L2CAP API code
     22  *
     23  ******************************************************************************/
     24 
     25 #define LOG_TAG "bt_l2cap"
     26 
     27 #include <base/logging.h>
     28 #include <base/strings/stringprintf.h>
     29 #include <stdio.h>
     30 #include <stdlib.h>
     31 #include <string.h>
     32 
     33 #include "bt_common.h"
     34 #include "bt_types.h"
     35 #include "btm_api.h"
     36 #include "btu.h"
     37 #include "device/include/controller.h"
     38 #include "hcidefs.h"
     39 #include "hcimsgs.h"
     40 #include "l2c_int.h"
     41 #include "l2cdefs.h"
     42 #include "osi/include/allocator.h"
     43 #include "osi/include/log.h"
     44 
     45 using base::StringPrintf;
     46 
     47 /*******************************************************************************
     48  *
     49  * Function         L2CA_Register
     50  *
     51  * Description      Other layers call this function to register for L2CAP
     52  *                  services.
     53  *
     54  * Returns          PSM to use or zero if error. Typically, the PSM returned
     55  *                  is the same as was passed in, but for an outgoing-only
     56  *                  connection to a dynamic PSM, a "virtual" PSM is returned
     57  *                  and should be used in the calls to L2CA_ConnectReq(),
     58  *                  L2CA_ErtmConnectReq() and L2CA_Deregister()
     59  *
     60  ******************************************************************************/
     61 uint16_t L2CA_Register(uint16_t psm, tL2CAP_APPL_INFO* p_cb_info) {
     62   tL2C_RCB* p_rcb;
     63   uint16_t vpsm = psm;
     64 
     65   L2CAP_TRACE_API("L2CAP - L2CA_Register() called for PSM: 0x%04x", psm);
     66 
     67   /* Verify that the required callback info has been filled in
     68   **      Note:  Connection callbacks are required but not checked
     69   **             for here because it is possible to be only a client
     70   **             or only a server.
     71   */
     72   if ((!p_cb_info->pL2CA_ConfigCfm_Cb) || (!p_cb_info->pL2CA_ConfigInd_Cb) ||
     73       (!p_cb_info->pL2CA_DataInd_Cb) || (!p_cb_info->pL2CA_DisconnectInd_Cb)) {
     74     L2CAP_TRACE_ERROR("L2CAP - no cb registering PSM: 0x%04x", psm);
     75     return (0);
     76   }
     77 
     78   /* Verify PSM is valid */
     79   if (L2C_INVALID_PSM(psm)) {
     80     L2CAP_TRACE_ERROR("L2CAP - invalid PSM value, PSM: 0x%04x", psm);
     81     return (0);
     82   }
     83 
     84   /* Check if this is a registration for an outgoing-only connection to */
     85   /* a dynamic PSM. If so, allocate a "virtual" PSM for the app to use. */
     86   if ((psm >= 0x1001) && (p_cb_info->pL2CA_ConnectInd_Cb == NULL)) {
     87     for (vpsm = 0x1002; vpsm < 0x8000; vpsm += 2) {
     88       p_rcb = l2cu_find_rcb_by_psm(vpsm);
     89       if (p_rcb == NULL) break;
     90     }
     91 
     92     L2CAP_TRACE_API("L2CA_Register - Real PSM: 0x%04x  Virtual PSM: 0x%04x",
     93                     psm, vpsm);
     94   }
     95 
     96   /* If registration block already there, just overwrite it */
     97   p_rcb = l2cu_find_rcb_by_psm(vpsm);
     98   if (p_rcb == NULL) {
     99     p_rcb = l2cu_allocate_rcb(vpsm);
    100     if (p_rcb == NULL) {
    101       L2CAP_TRACE_WARNING("L2CAP - no RCB available, PSM: 0x%04x  vPSM: 0x%04x",
    102                           psm, vpsm);
    103       return (0);
    104     }
    105   }
    106 
    107   p_rcb->api = *p_cb_info;
    108   p_rcb->real_psm = psm;
    109 
    110   return (vpsm);
    111 }
    112 
    113 /*******************************************************************************
    114  *
    115  * Function         L2CA_Deregister
    116  *
    117  * Description      Other layers call this function to de-register for L2CAP
    118  *                  services.
    119  *
    120  * Returns          void
    121  *
    122  ******************************************************************************/
    123 void L2CA_Deregister(uint16_t psm) {
    124   tL2C_RCB* p_rcb;
    125   tL2C_CCB* p_ccb;
    126   tL2C_LCB* p_lcb;
    127   int ii;
    128 
    129   L2CAP_TRACE_API("L2CAP - L2CA_Deregister() called for PSM: 0x%04x", psm);
    130 
    131   p_rcb = l2cu_find_rcb_by_psm(psm);
    132   if (p_rcb != NULL) {
    133     p_lcb = &l2cb.lcb_pool[0];
    134     for (ii = 0; ii < MAX_L2CAP_LINKS; ii++, p_lcb++) {
    135       if (p_lcb->in_use) {
    136         p_ccb = p_lcb->ccb_queue.p_first_ccb;
    137         if ((p_ccb == NULL) || (p_lcb->link_state == LST_DISCONNECTING)) {
    138           continue;
    139         }
    140 
    141         if ((p_ccb->in_use) &&
    142             ((p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP) ||
    143              (p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))) {
    144           continue;
    145         }
    146 
    147         if (p_ccb->p_rcb == p_rcb) {
    148           l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL);
    149         }
    150       }
    151     }
    152     l2cu_release_rcb(p_rcb);
    153   } else {
    154     L2CAP_TRACE_WARNING("L2CAP - PSM: 0x%04x not found for deregistration",
    155                         psm);
    156   }
    157 }
    158 
    159 /*******************************************************************************
    160  *
    161  * Function         L2CA_AllocatePSM
    162  *
    163  * Description      Other layers call this function to find an unused PSM for
    164  *                  L2CAP services.
    165  *
    166  * Returns          PSM to use.
    167  *
    168  ******************************************************************************/
    169 uint16_t L2CA_AllocatePSM(void) {
    170   bool done = false;
    171   uint16_t psm = l2cb.dyn_psm;
    172 
    173   L2CAP_TRACE_API("L2CA_AllocatePSM");
    174   while (!done) {
    175     psm += 2;
    176     if (psm > 0xfeff) {
    177       psm = 0x1001;
    178     } else if (psm & 0x0100) {
    179       /* the upper byte must be even */
    180       psm += 0x0100;
    181     }
    182 
    183     /* if psm is in range of reserved BRCM Aware features */
    184     if ((BRCM_RESERVED_PSM_START <= psm) && (psm <= BRCM_RESERVED_PSM_END))
    185       continue;
    186 
    187     /* make sure the newlly allocated psm is not used right now */
    188     if ((l2cu_find_rcb_by_psm(psm)) == NULL) done = true;
    189   }
    190   l2cb.dyn_psm = psm;
    191 
    192   return (psm);
    193 }
    194 
    195 /*******************************************************************************
    196  *
    197  * Function         L2CA_AllocateLePSM
    198  *
    199  * Description      To find an unused LE PSM for L2CAP services.
    200  *
    201  * Returns          LE_PSM to use if success. Otherwise returns 0.
    202  *
    203  ******************************************************************************/
    204 uint16_t L2CA_AllocateLePSM(void) {
    205   bool done = false;
    206   uint16_t psm = l2cb.le_dyn_psm;
    207   uint16_t count = 0;
    208 
    209   L2CAP_TRACE_API("%s: last psm=%d", __func__, psm);
    210   while (!done) {
    211     count++;
    212     if (count > LE_DYNAMIC_PSM_RANGE) {
    213       L2CAP_TRACE_ERROR("%s: Out of free BLE PSM", __func__);
    214       return 0;
    215     }
    216 
    217     psm++;
    218     if (psm > LE_DYNAMIC_PSM_END) {
    219       psm = LE_DYNAMIC_PSM_START;
    220     }
    221 
    222     if (!l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START]) {
    223       /* make sure the newly allocated psm is not used right now */
    224       if (l2cu_find_ble_rcb_by_psm(psm)) {
    225         L2CAP_TRACE_WARNING("%s: supposedly-free PSM=%d have allocated rcb!",
    226                             __func__, psm);
    227         continue;
    228       }
    229 
    230       l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START] = true;
    231       L2CAP_TRACE_DEBUG("%s: assigned PSM=%d", __func__, psm);
    232       done = true;
    233       break;
    234     }
    235   }
    236   l2cb.le_dyn_psm = psm;
    237 
    238   return (psm);
    239 }
    240 
    241 /*******************************************************************************
    242  *
    243  * Function         L2CA_FreeLePSM
    244  *
    245  * Description      Free an assigned LE PSM.
    246  *
    247  * Returns          void
    248  *
    249  ******************************************************************************/
    250 void L2CA_FreeLePSM(uint16_t psm) {
    251   L2CAP_TRACE_API("%s: to free psm=%d", __func__, psm);
    252 
    253   if ((psm < LE_DYNAMIC_PSM_START) || (psm > LE_DYNAMIC_PSM_END)) {
    254     L2CAP_TRACE_ERROR("%s: Invalid PSM=%d value!", __func__, psm);
    255     return;
    256   }
    257 
    258   if (!l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START]) {
    259     L2CAP_TRACE_WARNING("%s: PSM=%d was not allocated!", __func__, psm);
    260   }
    261   l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START] = false;
    262 }
    263 
    264 /*******************************************************************************
    265  *
    266  * Function         L2CA_ConnectReq
    267  *
    268  * Description      Higher layers call this function to create an L2CAP
    269  *                  connection. Note that the connection is not established at
    270  *                  this time, but connection establishment gets started. The
    271  *                  callback function will be invoked when connection
    272  *                  establishes or fails.
    273  *
    274  * Returns          the CID of the connection, or 0 if it failed to start
    275  *
    276  ******************************************************************************/
    277 uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr) {
    278   return L2CA_ErtmConnectReq(psm, p_bd_addr, NULL);
    279 }
    280 
    281 /*******************************************************************************
    282  *
    283  * Function         L2CA_ErtmConnectReq
    284  *
    285  * Description      Higher layers call this function to create an L2CAP
    286  *                  connection. Note that the connection is not established at
    287  *                  this time, but connection establishment gets started. The
    288  *                  callback function will be invoked when connection
    289  *                  establishes or fails.
    290  *
    291  *  Parameters:       PSM: L2CAP PSM for the connection
    292  *                    BD address of the peer
    293  *                   Enhaced retransmission mode configurations
    294 
    295  * Returns          the CID of the connection, or 0 if it failed to start
    296  *
    297  ******************************************************************************/
    298 uint16_t L2CA_ErtmConnectReq(uint16_t psm, const RawAddress& p_bd_addr,
    299                              tL2CAP_ERTM_INFO* p_ertm_info) {
    300   tL2C_LCB* p_lcb;
    301   tL2C_CCB* p_ccb;
    302   tL2C_RCB* p_rcb;
    303 
    304   VLOG(1) << __func__ << "BDA " << p_bd_addr
    305           << StringPrintf(" PSM: 0x%04x allowed:0x%x preferred:%d", psm,
    306                           (p_ertm_info) ? p_ertm_info->allowed_modes : 0,
    307                           (p_ertm_info) ? p_ertm_info->preferred_mode : 0);
    308 
    309   /* Fail if we have not established communications with the controller */
    310   if (!BTM_IsDeviceUp()) {
    311     L2CAP_TRACE_WARNING("L2CAP connect req - BTU not ready");
    312     return (0);
    313   }
    314   /* Fail if the PSM is not registered */
    315   p_rcb = l2cu_find_rcb_by_psm(psm);
    316   if (p_rcb == NULL) {
    317     L2CAP_TRACE_WARNING("L2CAP - no RCB for L2CA_conn_req, PSM: 0x%04x", psm);
    318     return (0);
    319   }
    320 
    321   /* First, see if we already have a link to the remote */
    322   /* assume all ERTM l2cap connection is going over BR/EDR for now */
    323   p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_BR_EDR);
    324   if (p_lcb == NULL) {
    325     /* No link. Get an LCB and start link establishment */
    326     p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_BR_EDR);
    327     /* currently use BR/EDR for ERTM mode l2cap connection */
    328     if ((p_lcb == NULL) || (!l2cu_create_conn(p_lcb, BT_TRANSPORT_BR_EDR))) {
    329       L2CAP_TRACE_WARNING(
    330           "L2CAP - conn not started for PSM: 0x%04x  p_lcb: 0x%08x", psm,
    331           p_lcb);
    332       return (0);
    333     }
    334   }
    335 
    336   /* Allocate a channel control block */
    337   p_ccb = l2cu_allocate_ccb(p_lcb, 0);
    338   if (p_ccb == NULL) {
    339     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_conn_req, PSM: 0x%04x", psm);
    340     return (0);
    341   }
    342 
    343   /* Save registration info */
    344   p_ccb->p_rcb = p_rcb;
    345 
    346   if (p_ertm_info) {
    347     p_ccb->ertm_info = *p_ertm_info;
    348 
    349     /* Replace default indicators with the actual default pool */
    350     if (p_ccb->ertm_info.fcr_rx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    351       p_ccb->ertm_info.fcr_rx_buf_size = L2CAP_FCR_RX_BUF_SIZE;
    352 
    353     if (p_ccb->ertm_info.fcr_tx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    354       p_ccb->ertm_info.fcr_tx_buf_size = L2CAP_FCR_TX_BUF_SIZE;
    355 
    356     if (p_ccb->ertm_info.user_rx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    357       p_ccb->ertm_info.user_rx_buf_size = L2CAP_USER_RX_BUF_SIZE;
    358 
    359     if (p_ccb->ertm_info.user_tx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    360       p_ccb->ertm_info.user_tx_buf_size = L2CAP_USER_TX_BUF_SIZE;
    361 
    362     p_ccb->max_rx_mtu =
    363         p_ertm_info->user_rx_buf_size -
    364         (L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET + L2CAP_FCS_LEN);
    365   }
    366 
    367   /* If link is up, start the L2CAP connection */
    368   if (p_lcb->link_state == LST_CONNECTED) {
    369     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_REQ, NULL);
    370   }
    371 
    372   /* If link is disconnecting, save link info to retry after disconnect
    373    * Possible Race condition when a reconnect occurs
    374    * on the channel during a disconnect of link. This
    375    * ccb will be automatically retried after link disconnect
    376    * arrives
    377    */
    378   else if (p_lcb->link_state == LST_DISCONNECTING) {
    379     L2CAP_TRACE_DEBUG("L2CAP API - link disconnecting: RETRY LATER");
    380 
    381     /* Save ccb so it can be started after disconnect is finished */
    382     p_lcb->p_pending_ccb = p_ccb;
    383   }
    384 
    385   L2CAP_TRACE_API("L2CAP - L2CA_conn_req(psm: 0x%04x) returned CID: 0x%04x",
    386                   psm, p_ccb->local_cid);
    387 
    388   /* Return the local CID as our handle */
    389   return (p_ccb->local_cid);
    390 }
    391 
    392 /*******************************************************************************
    393  *
    394  * Function         L2CA_RegisterLECoc
    395  *
    396  * Description      Other layers call this function to register for L2CAP
    397  *                  Connection Oriented Channel.
    398  *
    399  * Returns          PSM to use or zero if error. Typically, the PSM returned
    400  *                  is the same as was passed in, but for an outgoing-only
    401  *                  connection to a dynamic PSM, a "virtual" PSM is returned
    402  *                  and should be used in the calls to L2CA_ConnectLECocReq()
    403  *                  and L2CA_DeregisterLECoc()
    404  *
    405  ******************************************************************************/
    406 uint16_t L2CA_RegisterLECoc(uint16_t psm, tL2CAP_APPL_INFO* p_cb_info) {
    407   L2CAP_TRACE_API("%s called for LE PSM: 0x%04x", __func__, psm);
    408 
    409   /* Verify that the required callback info has been filled in
    410   **      Note:  Connection callbacks are required but not checked
    411   **             for here because it is possible to be only a client
    412   **             or only a server.
    413   */
    414   if ((!p_cb_info->pL2CA_DataInd_Cb) || (!p_cb_info->pL2CA_DisconnectInd_Cb)) {
    415     L2CAP_TRACE_ERROR("%s No cb registering BLE PSM: 0x%04x", __func__, psm);
    416     return 0;
    417   }
    418 
    419   /* Verify PSM is valid */
    420   if (!L2C_IS_VALID_LE_PSM(psm)) {
    421     L2CAP_TRACE_ERROR("%s Invalid BLE PSM value, PSM: 0x%04x", __func__, psm);
    422     return 0;
    423   }
    424 
    425   tL2C_RCB* p_rcb;
    426   uint16_t vpsm = psm;
    427 
    428   /* Check if this is a registration for an outgoing-only connection to */
    429   /* a dynamic PSM. If so, allocate a "virtual" PSM for the app to use. */
    430   if ((psm >= LE_DYNAMIC_PSM_START) &&
    431       (p_cb_info->pL2CA_ConnectInd_Cb == NULL)) {
    432     vpsm = L2CA_AllocateLePSM();
    433     if (vpsm == 0) {
    434       L2CAP_TRACE_ERROR("%s: Out of free BLE PSM", __func__);
    435       return 0;
    436     }
    437 
    438     L2CAP_TRACE_API("%s Real PSM: 0x%04x  Virtual PSM: 0x%04x", __func__, psm,
    439                     vpsm);
    440   }
    441 
    442   /* If registration block already there, just overwrite it */
    443   p_rcb = l2cu_find_ble_rcb_by_psm(vpsm);
    444   if (p_rcb == NULL) {
    445     L2CAP_TRACE_API("%s Allocate rcp for Virtual PSM: 0x%04x", __func__, vpsm);
    446     p_rcb = l2cu_allocate_ble_rcb(vpsm);
    447     if (p_rcb == NULL) {
    448       L2CAP_TRACE_WARNING("%s No BLE RCB available, PSM: 0x%04x  vPSM: 0x%04x",
    449                           __func__, psm, vpsm);
    450       return 0;
    451     }
    452   }
    453 
    454   p_rcb->api = *p_cb_info;
    455   p_rcb->real_psm = psm;
    456 
    457   return vpsm;
    458 }
    459 
    460 /*******************************************************************************
    461  *
    462  * Function         L2CA_DeregisterLECoc
    463  *
    464  * Description      Other layers call this function to de-register for L2CAP
    465  *                  Connection Oriented Channel.
    466  *
    467  * Returns          void
    468  *
    469  ******************************************************************************/
    470 void L2CA_DeregisterLECoc(uint16_t psm) {
    471   L2CAP_TRACE_API("%s called for PSM: 0x%04x", __func__, psm);
    472 
    473   tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
    474   if (p_rcb == NULL) {
    475     L2CAP_TRACE_WARNING("%s PSM: 0x%04x not found for deregistration", __func__,
    476                         psm);
    477     return;
    478   }
    479 
    480   tL2C_LCB* p_lcb = &l2cb.lcb_pool[0];
    481   for (int i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) {
    482     if (!p_lcb->in_use || p_lcb->transport != BT_TRANSPORT_LE) continue;
    483 
    484     tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb;
    485     if ((p_ccb == NULL) || (p_lcb->link_state == LST_DISCONNECTING)) continue;
    486 
    487     if (p_ccb->in_use && (p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP ||
    488                           p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))
    489       continue;
    490 
    491     if (p_ccb->p_rcb == p_rcb)
    492       l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL);
    493   }
    494 
    495   l2cu_release_ble_rcb(p_rcb);
    496 }
    497 
    498 /*******************************************************************************
    499  *
    500  * Function         L2CA_ConnectLECocReq
    501  *
    502  * Description      Higher layers call this function to create an L2CAP
    503  *                  connection. Note that the connection is not established at
    504  *                  this time, but connection establishment gets started. The
    505  *                  callback function will be invoked when connection
    506  *                  establishes or fails.
    507  *
    508  *  Parameters:     PSM: L2CAP PSM for the connection
    509  *                  BD address of the peer
    510  *                  Local Coc configurations
    511 
    512  * Returns          the CID of the connection, or 0 if it failed to start
    513  *
    514  ******************************************************************************/
    515 uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr,
    516                               tL2CAP_LE_CFG_INFO* p_cfg) {
    517   VLOG(1) << __func__ << " BDA: " << p_bd_addr
    518           << StringPrintf(" PSM: 0x%04x", psm);
    519 
    520   /* Fail if we have not established communications with the controller */
    521   if (!BTM_IsDeviceUp()) {
    522     L2CAP_TRACE_WARNING("%s BTU not ready", __func__);
    523     return 0;
    524   }
    525 
    526   /* Fail if the PSM is not registered */
    527   tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
    528   if (p_rcb == NULL) {
    529     L2CAP_TRACE_WARNING("%s No BLE RCB, PSM: 0x%04x", __func__, psm);
    530     return 0;
    531   }
    532 
    533   /* First, see if we already have a le link to the remote */
    534   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE);
    535   if (p_lcb == NULL) {
    536     /* No link. Get an LCB and start link establishment */
    537     p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_LE);
    538     if ((p_lcb == NULL)
    539         /* currently use BR/EDR for ERTM mode l2cap connection */
    540         || (!l2cu_create_conn(p_lcb, BT_TRANSPORT_LE))) {
    541       L2CAP_TRACE_WARNING("%s conn not started for PSM: 0x%04x  p_lcb: 0x%08x",
    542                           __func__, psm, p_lcb);
    543       return 0;
    544     }
    545   }
    546 
    547   /* Allocate a channel control block */
    548   tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
    549   if (p_ccb == NULL) {
    550     L2CAP_TRACE_WARNING("%s no CCB, PSM: 0x%04x", __func__, psm);
    551     return 0;
    552   }
    553 
    554   /* Save registration info */
    555   p_ccb->p_rcb = p_rcb;
    556 
    557   /* Save the configuration */
    558   if (p_cfg) {
    559     memcpy(&p_ccb->local_conn_cfg, p_cfg, sizeof(tL2CAP_LE_CFG_INFO));
    560     p_ccb->remote_credit_count = p_cfg->credits;
    561   }
    562 
    563   /* If link is up, start the L2CAP connection */
    564   if (p_lcb->link_state == LST_CONNECTED) {
    565     if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
    566       L2CAP_TRACE_DEBUG("%s LE Link is up", __func__);
    567       l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_REQ, NULL);
    568     }
    569   }
    570 
    571   /* If link is disconnecting, save link info to retry after disconnect
    572    * Possible Race condition when a reconnect occurs
    573    * on the channel during a disconnect of link. This
    574    * ccb will be automatically retried after link disconnect
    575    * arrives
    576    */
    577   else if (p_lcb->link_state == LST_DISCONNECTING) {
    578     L2CAP_TRACE_DEBUG("%s link disconnecting: RETRY LATER", __func__);
    579 
    580     /* Save ccb so it can be started after disconnect is finished */
    581     p_lcb->p_pending_ccb = p_ccb;
    582   }
    583 
    584   L2CAP_TRACE_API("%s(psm: 0x%04x) returned CID: 0x%04x", __func__, psm,
    585                   p_ccb->local_cid);
    586 
    587   /* Return the local CID as our handle */
    588   return p_ccb->local_cid;
    589 }
    590 
    591 /*******************************************************************************
    592  *
    593  * Function         L2CA_ConnectLECocRsp
    594  *
    595  * Description      Higher layers call this function to accept an incoming
    596  *                  L2CAP COC connection, for which they had gotten an connect
    597  *                  indication callback.
    598  *
    599  * Returns          true for success, false for failure
    600  *
    601  ******************************************************************************/
    602 bool L2CA_ConnectLECocRsp(const RawAddress& p_bd_addr, uint8_t id,
    603                           uint16_t lcid, uint16_t result, uint16_t status,
    604                           tL2CAP_LE_CFG_INFO* p_cfg) {
    605   VLOG(1) << __func__ << " BDA: " << p_bd_addr
    606           << StringPrintf(" CID: 0x%04x Result: %d Status: %d", lcid, result,
    607                           status);
    608 
    609   /* First, find the link control block */
    610   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE);
    611   if (p_lcb == NULL) {
    612     /* No link. Get an LCB and start link establishment */
    613     L2CAP_TRACE_WARNING("%s no LCB", __func__);
    614     return false;
    615   }
    616 
    617   /* Now, find the channel control block */
    618   tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
    619   if (p_ccb == NULL) {
    620     L2CAP_TRACE_WARNING("%s no CCB", __func__);
    621     return false;
    622   }
    623 
    624   /* The IDs must match */
    625   if (p_ccb->remote_id != id) {
    626     L2CAP_TRACE_WARNING("%s bad id. Expected: %d  Got: %d", __func__,
    627                         p_ccb->remote_id, id);
    628     return false;
    629   }
    630 
    631   if (p_cfg) {
    632     memcpy(&p_ccb->local_conn_cfg, p_cfg, sizeof(tL2CAP_LE_CFG_INFO));
    633     p_ccb->remote_credit_count = p_cfg->credits;
    634   }
    635 
    636   if (result == L2CAP_CONN_OK)
    637     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_RSP, NULL);
    638   else {
    639     tL2C_CONN_INFO conn_info;
    640     conn_info.bd_addr = p_bd_addr;
    641     conn_info.l2cap_result = result;
    642     conn_info.l2cap_status = status;
    643     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_RSP_NEG, &conn_info);
    644   }
    645 
    646   return true;
    647 }
    648 
    649 /*******************************************************************************
    650  *
    651  *  Function         L2CA_GetPeerLECocConfig
    652  *
    653  *  Description      Get a peers configuration for LE Connection Oriented
    654  *                   Channel.
    655  *
    656  *  Parameters:      local channel id
    657  *                   Pointers to peers configuration storage area
    658  *
    659  *  Return value:    true if peer is connected
    660  *
    661  ******************************************************************************/
    662 bool L2CA_GetPeerLECocConfig(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg) {
    663   L2CAP_TRACE_API("%s CID: 0x%04x", __func__, lcid);
    664 
    665   tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
    666   if (p_ccb == NULL) {
    667     L2CAP_TRACE_ERROR("%s No CCB for CID:0x%04x", __func__, lcid);
    668     return false;
    669   }
    670 
    671   if (peer_cfg != NULL)
    672     memcpy(peer_cfg, &p_ccb->peer_conn_cfg, sizeof(tL2CAP_LE_CFG_INFO));
    673 
    674   return true;
    675 }
    676 
    677 bool L2CA_SetConnectionCallbacks(uint16_t local_cid,
    678                                  const tL2CAP_APPL_INFO* callbacks) {
    679   CHECK(callbacks != NULL);
    680   CHECK(callbacks->pL2CA_ConnectInd_Cb == NULL);
    681   CHECK(callbacks->pL2CA_ConnectCfm_Cb != NULL);
    682   CHECK(callbacks->pL2CA_ConfigInd_Cb != NULL);
    683   CHECK(callbacks->pL2CA_ConfigCfm_Cb != NULL);
    684   CHECK(callbacks->pL2CA_DisconnectInd_Cb != NULL);
    685   CHECK(callbacks->pL2CA_DisconnectCfm_Cb != NULL);
    686   CHECK(callbacks->pL2CA_CongestionStatus_Cb != NULL);
    687   CHECK(callbacks->pL2CA_DataInd_Cb != NULL);
    688   CHECK(callbacks->pL2CA_TxComplete_Cb != NULL);
    689 
    690   tL2C_CCB* channel_control_block = l2cu_find_ccb_by_cid(NULL, local_cid);
    691   if (!channel_control_block) {
    692     LOG_ERROR(LOG_TAG,
    693               "%s no channel control block found for L2CAP LCID=0x%04x.",
    694               __func__, local_cid);
    695     return false;
    696   }
    697 
    698   // We're making a connection-specific registration control block so we check
    699   // if we already have a private one allocated to us on the heap. If not, we
    700   // make a new allocation, mark it as heap-allocated, and inherit the fields
    701   // from the old control block.
    702   tL2C_RCB* registration_control_block = channel_control_block->p_rcb;
    703   if (!channel_control_block->should_free_rcb) {
    704     registration_control_block = (tL2C_RCB*)osi_calloc(sizeof(tL2C_RCB));
    705 
    706     *registration_control_block = *channel_control_block->p_rcb;
    707     channel_control_block->p_rcb = registration_control_block;
    708     channel_control_block->should_free_rcb = true;
    709   }
    710 
    711   registration_control_block->api = *callbacks;
    712   return true;
    713 }
    714 
    715 /*******************************************************************************
    716  *
    717  * Function         L2CA_ConnectRsp
    718  *
    719  * Description      Higher layers call this function to accept an incoming
    720  *                  L2CAP connection, for which they had gotten an connect
    721  *                  indication callback.
    722  *
    723  * Returns          true for success, false for failure
    724  *
    725  ******************************************************************************/
    726 bool L2CA_ConnectRsp(const RawAddress& p_bd_addr, uint8_t id, uint16_t lcid,
    727                      uint16_t result, uint16_t status) {
    728   return L2CA_ErtmConnectRsp(p_bd_addr, id, lcid, result, status, NULL);
    729 }
    730 
    731 /*******************************************************************************
    732  *
    733  * Function         L2CA_ErtmConnectRsp
    734  *
    735  * Description      Higher layers call this function to accept an incoming
    736  *                  L2CAP connection, for which they had gotten an connect
    737  *                  indication callback.
    738  *
    739  * Returns          true for success, false for failure
    740  *
    741  ******************************************************************************/
    742 bool L2CA_ErtmConnectRsp(const RawAddress& p_bd_addr, uint8_t id, uint16_t lcid,
    743                          uint16_t result, uint16_t status,
    744                          tL2CAP_ERTM_INFO* p_ertm_info) {
    745   tL2C_LCB* p_lcb;
    746   tL2C_CCB* p_ccb;
    747 
    748   VLOG(1) << __func__ << " BDA: " << p_bd_addr
    749           << StringPrintf(" CID:0x%04x  Result:%d  Status:%d", lcid, result,
    750                           status);
    751 
    752   /* First, find the link control block */
    753   p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_BR_EDR);
    754   if (p_lcb == NULL) {
    755     /* No link. Get an LCB and start link establishment */
    756     L2CAP_TRACE_WARNING("L2CAP - no LCB for L2CA_conn_rsp");
    757     return (false);
    758   }
    759 
    760   /* Now, find the channel control block */
    761   p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
    762   if (p_ccb == NULL) {
    763     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_conn_rsp");
    764     return (false);
    765   }
    766 
    767   /* The IDs must match */
    768   if (p_ccb->remote_id != id) {
    769     L2CAP_TRACE_WARNING("L2CAP - bad id in L2CA_conn_rsp. Exp: %d  Got: %d",
    770                         p_ccb->remote_id, id);
    771     return (false);
    772   }
    773 
    774   if (p_ertm_info) {
    775     p_ccb->ertm_info = *p_ertm_info;
    776 
    777     /* Replace default indicators with the actual default pool */
    778     if (p_ccb->ertm_info.fcr_rx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    779       p_ccb->ertm_info.fcr_rx_buf_size = L2CAP_FCR_RX_BUF_SIZE;
    780 
    781     if (p_ccb->ertm_info.fcr_tx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    782       p_ccb->ertm_info.fcr_tx_buf_size = L2CAP_FCR_TX_BUF_SIZE;
    783 
    784     if (p_ccb->ertm_info.user_rx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    785       p_ccb->ertm_info.user_rx_buf_size = L2CAP_USER_RX_BUF_SIZE;
    786 
    787     if (p_ccb->ertm_info.user_tx_buf_size == L2CAP_INVALID_ERM_BUF_SIZE)
    788       p_ccb->ertm_info.user_tx_buf_size = L2CAP_USER_TX_BUF_SIZE;
    789 
    790     p_ccb->max_rx_mtu =
    791         p_ertm_info->user_rx_buf_size -
    792         (L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET + L2CAP_FCS_LEN);
    793   }
    794 
    795   if (result == L2CAP_CONN_OK) {
    796     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_RSP, NULL);
    797   } else {
    798     tL2C_CONN_INFO conn_info;
    799 
    800     conn_info.l2cap_result = result;
    801     conn_info.l2cap_status = status;
    802 
    803     if (result == L2CAP_CONN_PENDING)
    804       l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_RSP, &conn_info);
    805     else
    806       l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_RSP_NEG, &conn_info);
    807   }
    808 
    809   return (true);
    810 }
    811 
    812 /*******************************************************************************
    813  *
    814  * Function         L2CA_ConfigReq
    815  *
    816  * Description      Higher layers call this function to send configuration.
    817  *
    818  *                  Note:  The FCR options of p_cfg are not used.
    819  *
    820  * Returns          true if configuration sent, else false
    821  *
    822  ******************************************************************************/
    823 bool L2CA_ConfigReq(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) {
    824   tL2C_CCB* p_ccb;
    825 
    826   L2CAP_TRACE_API(
    827       "L2CA_ConfigReq()  CID 0x%04x: fcr_present:%d (mode %d) mtu_present:%d "
    828       "(%d)",
    829       cid, p_cfg->fcr_present, p_cfg->fcr.mode, p_cfg->mtu_present, p_cfg->mtu);
    830 
    831   /* Find the channel control block. We don't know the link it is on. */
    832   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
    833   if (p_ccb == NULL) {
    834     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_cfg_req, CID: %d", cid);
    835     return (false);
    836   }
    837 
    838   /* We need to have at least one mode type common with the peer */
    839   if (!l2c_fcr_adj_our_req_options(p_ccb, p_cfg)) return (false);
    840 
    841   /* Don't adjust FCR options if not used */
    842   if ((!p_cfg->fcr_present) || (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE)) {
    843     /* FCR and FCS options are not used in basic mode */
    844     p_cfg->fcs_present = false;
    845     p_cfg->ext_flow_spec_present = false;
    846 
    847     if ((p_cfg->mtu_present) && (p_cfg->mtu > L2CAP_MTU_SIZE)) {
    848       L2CAP_TRACE_WARNING("L2CAP - adjust MTU: %u too large", p_cfg->mtu);
    849       p_cfg->mtu = L2CAP_MTU_SIZE;
    850     }
    851   }
    852 
    853   /* Save the adjusted configuration in case it needs to be used for
    854    * renegotiation */
    855   p_ccb->our_cfg = *p_cfg;
    856 
    857   l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONFIG_REQ, p_cfg);
    858 
    859   return (true);
    860 }
    861 
    862 /*******************************************************************************
    863  *
    864  * Function         L2CA_ConfigRsp
    865  *
    866  * Description      Higher layers call this function to send a configuration
    867  *                  response.
    868  *
    869  * Returns          true if configuration response sent, else false
    870  *
    871  ******************************************************************************/
    872 bool L2CA_ConfigRsp(uint16_t cid, tL2CAP_CFG_INFO* p_cfg) {
    873   tL2C_CCB* p_ccb;
    874 
    875   L2CAP_TRACE_API(
    876       "L2CA_ConfigRsp()  CID: 0x%04x  Result: %d MTU present:%d Flush TO:%d "
    877       "FCR:%d FCS:%d",
    878       cid, p_cfg->result, p_cfg->mtu_present, p_cfg->flush_to_present,
    879       p_cfg->fcr_present, p_cfg->fcs_present);
    880 
    881   /* Find the channel control block. We don't know the link it is on. */
    882   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
    883   if (p_ccb == NULL) {
    884     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_cfg_rsp, CID: %d", cid);
    885     return (false);
    886   }
    887 
    888   if ((p_cfg->result == L2CAP_CFG_OK) || (p_cfg->result == L2CAP_CFG_PENDING))
    889     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONFIG_RSP, p_cfg);
    890   else {
    891     p_cfg->fcr_present =
    892         false; /* FCR options already negotiated before this point */
    893 
    894     /* Clear out any cached options that are being returned as an error
    895      * (excluding FCR) */
    896     if (p_cfg->mtu_present) p_ccb->peer_cfg.mtu_present = false;
    897     if (p_cfg->flush_to_present) p_ccb->peer_cfg.flush_to_present = false;
    898     if (p_cfg->qos_present) p_ccb->peer_cfg.qos_present = false;
    899 
    900     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONFIG_RSP_NEG, p_cfg);
    901   }
    902 
    903   return (true);
    904 }
    905 
    906 /*******************************************************************************
    907  *
    908  * Function         L2CA_DisconnectReq
    909  *
    910  * Description      Higher layers call this function to disconnect a channel.
    911  *
    912  * Returns          true if disconnect sent, else false
    913  *
    914  ******************************************************************************/
    915 bool L2CA_DisconnectReq(uint16_t cid) {
    916   tL2C_CCB* p_ccb;
    917 
    918   L2CAP_TRACE_API("L2CA_DisconnectReq()  CID: 0x%04x", cid);
    919 
    920   /* Find the channel control block. We don't know the link it is on. */
    921   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
    922   if (p_ccb == NULL) {
    923     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_disc_req, CID: %d", cid);
    924     return (false);
    925   }
    926 
    927   l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL);
    928 
    929   return (true);
    930 }
    931 
    932 /*******************************************************************************
    933  *
    934  * Function         L2CA_DisconnectRsp
    935  *
    936  * Description      Higher layers call this function to acknowledge the
    937  *                  disconnection of a channel.
    938  *
    939  * Returns          void
    940  *
    941  ******************************************************************************/
    942 bool L2CA_DisconnectRsp(uint16_t cid) {
    943   tL2C_CCB* p_ccb;
    944 
    945   L2CAP_TRACE_API("L2CA_DisconnectRsp()  CID: 0x%04x", cid);
    946 
    947   /* Find the channel control block. We don't know the link it is on. */
    948   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
    949   if (p_ccb == NULL) {
    950     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_disc_rsp, CID: %d", cid);
    951     return (false);
    952   }
    953 
    954   l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_RSP, NULL);
    955 
    956   return (true);
    957 }
    958 
    959 /*******************************************************************************
    960  *
    961  * Function         L2CA_Ping
    962  *
    963  * Description      Higher layers call this function to send an echo request.
    964  *
    965  * Returns          true if echo request sent, else false.
    966  *
    967  ******************************************************************************/
    968 bool L2CA_Ping(const RawAddress& p_bd_addr, tL2CA_ECHO_RSP_CB* p_callback) {
    969   tL2C_LCB* p_lcb;
    970 
    971   VLOG(1) << __func__ << " BDA: " << p_bd_addr;
    972 
    973   /* Fail if we have not established communications with the controller */
    974   if (!BTM_IsDeviceUp()) return (false);
    975 
    976   /* First, see if we already have a link to the remote */
    977   p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_BR_EDR);
    978   if (p_lcb == NULL) {
    979     /* No link. Get an LCB and start link establishment */
    980     p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_BR_EDR);
    981     if (p_lcb == NULL) {
    982       L2CAP_TRACE_WARNING("L2CAP - no LCB for L2CA_ping");
    983       return (false);
    984     }
    985     if (!l2cu_create_conn(p_lcb, BT_TRANSPORT_BR_EDR)) {
    986       return (false);
    987     }
    988 
    989     p_lcb->p_echo_rsp_cb = p_callback;
    990 
    991     return (true);
    992   }
    993 
    994   /* We only allow 1 ping outstanding at a time */
    995   if (p_lcb->p_echo_rsp_cb != NULL) {
    996     L2CAP_TRACE_WARNING("L2CAP - rejected second L2CA_ping");
    997     return (false);
    998   }
    999 
   1000   /* Have a link control block. If link is disconnecting, tell user to retry
   1001    * later */
   1002   if (p_lcb->link_state == LST_DISCONNECTING) {
   1003     L2CAP_TRACE_WARNING("L2CAP - L2CA_ping rejected - link disconnecting");
   1004     return (false);
   1005   }
   1006 
   1007   /* Save address of callback */
   1008   p_lcb->p_echo_rsp_cb = p_callback;
   1009 
   1010   if (p_lcb->link_state == LST_CONNECTED) {
   1011     l2cu_adj_id(p_lcb, L2CAP_ADJ_BRCM_ID); /* Make sure not using Broadcom ID */
   1012     l2cu_send_peer_echo_req(p_lcb, NULL, 0);
   1013     alarm_set_on_mloop(p_lcb->l2c_lcb_timer, L2CAP_ECHO_RSP_TIMEOUT_MS,
   1014                        l2c_lcb_timer_timeout, p_lcb);
   1015   }
   1016 
   1017   return (true);
   1018 }
   1019 
   1020 /*******************************************************************************
   1021  *
   1022  * Function         L2CA_Echo
   1023  *
   1024  * Description      Higher layers call this function to send an echo request
   1025  *                  with application-specific data.
   1026  *
   1027  * Returns          true if echo request sent, else false.
   1028  *
   1029  ******************************************************************************/
   1030 bool L2CA_Echo(const RawAddress& p_bd_addr, BT_HDR* p_data,
   1031                tL2CA_ECHO_DATA_CB* p_callback) {
   1032   tL2C_LCB* p_lcb;
   1033   uint8_t* pp;
   1034 
   1035   VLOG(1) << __func__ << " BDA: " << p_bd_addr;
   1036   ;
   1037 
   1038   /* Fail if we have not established communications with the controller */
   1039   if (!BTM_IsDeviceUp()) return (false);
   1040 
   1041   if (RawAddress::kAny == p_bd_addr && (p_data == NULL)) {
   1042     /* Only register callback without sending message. */
   1043     l2cb.p_echo_data_cb = p_callback;
   1044     return true;
   1045   }
   1046 
   1047   /* We assume the upper layer will call this function only when the link is
   1048    * established. */
   1049   p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_BR_EDR);
   1050   if (p_lcb == NULL) {
   1051     L2CAP_TRACE_ERROR("L2CA_Echo ERROR : link not established");
   1052     return false;
   1053   }
   1054 
   1055   if (p_lcb->link_state != LST_CONNECTED) {
   1056     L2CAP_TRACE_ERROR("L2CA_Echo ERROR : link is not connected");
   1057     return false;
   1058   }
   1059 
   1060   /* Save address of callback */
   1061   l2cb.p_echo_data_cb = p_callback;
   1062 
   1063   /* Set the pointer to the beginning of the data */
   1064   pp = (uint8_t*)(p_data + 1) + p_data->offset;
   1065   l2cu_adj_id(p_lcb, L2CAP_ADJ_BRCM_ID); /* Make sure not using Broadcom ID */
   1066   l2cu_send_peer_echo_req(p_lcb, pp, p_data->len);
   1067 
   1068   return (true);
   1069 }
   1070 
   1071 bool L2CA_GetIdentifiers(uint16_t lcid, uint16_t* rcid, uint16_t* handle) {
   1072   tL2C_CCB* control_block = l2cu_find_ccb_by_cid(NULL, lcid);
   1073   if (!control_block) return false;
   1074 
   1075   if (rcid) *rcid = control_block->remote_cid;
   1076   if (handle) *handle = control_block->p_lcb->handle;
   1077 
   1078   return true;
   1079 }
   1080 
   1081 /*******************************************************************************
   1082  *
   1083  * Function         L2CA_SetIdleTimeout
   1084  *
   1085  * Description      Higher layers call this function to set the idle timeout for
   1086  *                  a connection, or for all future connections. The "idle
   1087  *                  timeout" is the amount of time that a connection can remain
   1088  *                  up with no L2CAP channels on it. A timeout of zero means
   1089  *                  that the connection will be torn down immediately when the
   1090  *                  last channel is removed. A timeout of 0xFFFF means no
   1091  *                  timeout. Values are in seconds.
   1092  *
   1093  * Returns          true if command succeeded, false if failed
   1094  *
   1095  * NOTE             This timeout takes effect after at least 1 channel has been
   1096  *                  established and removed. L2CAP maintains its own timer from
   1097  *                  whan a connection is established till the first channel is
   1098  *                  set up.
   1099  ******************************************************************************/
   1100 bool L2CA_SetIdleTimeout(uint16_t cid, uint16_t timeout, bool is_global) {
   1101   tL2C_CCB* p_ccb;
   1102   tL2C_LCB* p_lcb;
   1103 
   1104   if (is_global) {
   1105     l2cb.idle_timeout = timeout;
   1106   } else {
   1107     /* Find the channel control block. We don't know the link it is on. */
   1108     p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
   1109     if (p_ccb == NULL) {
   1110       L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_SetIdleTimeout, CID: %d",
   1111                           cid);
   1112       return (false);
   1113     }
   1114 
   1115     p_lcb = p_ccb->p_lcb;
   1116 
   1117     if ((p_lcb) && (p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED))
   1118       p_lcb->idle_timeout = timeout;
   1119     else
   1120       return (false);
   1121   }
   1122 
   1123   return (true);
   1124 }
   1125 
   1126 /*******************************************************************************
   1127  *
   1128  * Function         L2CA_SetIdleTimeoutByBdAddr
   1129  *
   1130  * Description      Higher layers call this function to set the idle timeout for
   1131  *                  a connection. The "idle timeout" is the amount of time that
   1132  *                  a connection can remain up with no L2CAP channels on it.
   1133  *                  A timeout of zero means that the connection will be torn
   1134  *                  down immediately when the last channel is removed.
   1135  *                  A timeout of 0xFFFF means no timeout. Values are in seconds.
   1136  *                  A bd_addr is the remote BD address. If bd_addr =
   1137  *                  RawAddress::kAny, then the idle timeouts for all active
   1138  *                  l2cap links will be changed.
   1139  *
   1140  * Returns          true if command succeeded, false if failed
   1141  *
   1142  * NOTE             This timeout applies to all logical channels active on the
   1143  *                  ACL link.
   1144  ******************************************************************************/
   1145 bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr, uint16_t timeout,
   1146                                  tBT_TRANSPORT transport) {
   1147   tL2C_LCB* p_lcb;
   1148 
   1149   if (RawAddress::kAny != bd_addr) {
   1150     p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, transport);
   1151     if ((p_lcb) && (p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) {
   1152       p_lcb->idle_timeout = timeout;
   1153 
   1154       if (!p_lcb->ccb_queue.p_first_ccb) l2cu_no_dynamic_ccbs(p_lcb);
   1155     } else
   1156       return false;
   1157   } else {
   1158     int xx;
   1159     tL2C_LCB* p_lcb = &l2cb.lcb_pool[0];
   1160 
   1161     for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) {
   1162       if ((p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) {
   1163         p_lcb->idle_timeout = timeout;
   1164 
   1165         if (!p_lcb->ccb_queue.p_first_ccb) l2cu_no_dynamic_ccbs(p_lcb);
   1166       }
   1167     }
   1168   }
   1169 
   1170   return true;
   1171 }
   1172 
   1173 /*******************************************************************************
   1174  *
   1175  * Function         L2CA_SetTraceLevel
   1176  *
   1177  * Description      This function sets the trace level for L2CAP. If called with
   1178  *                  a value of 0xFF, it simply reads the current trace level.
   1179  *
   1180  * Returns          the new (current) trace level
   1181  *
   1182  ******************************************************************************/
   1183 uint8_t L2CA_SetTraceLevel(uint8_t new_level) {
   1184   if (new_level != 0xFF) l2cb.l2cap_trace_level = new_level;
   1185 
   1186   return (l2cb.l2cap_trace_level);
   1187 }
   1188 
   1189 /*******************************************************************************
   1190  *
   1191  * Function     L2CA_SetDesireRole
   1192  *
   1193  * Description  This function sets the desire role for L2CAP.
   1194  *              If the new role is L2CAP_ROLE_ALLOW_SWITCH, allow switch on
   1195  *              HciCreateConnection.
   1196  *              If the new role is L2CAP_ROLE_DISALLOW_SWITCH, do not allow
   1197  *              switch on HciCreateConnection.
   1198  *
   1199  *              If the new role is a valid role (HCI_ROLE_MASTER or
   1200  *              HCI_ROLE_SLAVE), the desire role is set to the new value.
   1201  *              Otherwise, it is not changed.
   1202  *
   1203  * Returns      the new (current) role
   1204  *
   1205  ******************************************************************************/
   1206 uint8_t L2CA_SetDesireRole(uint8_t new_role) {
   1207   L2CAP_TRACE_API("L2CA_SetDesireRole() new:x%x, disallow_switch:%d", new_role,
   1208                   l2cb.disallow_switch);
   1209 
   1210   if (L2CAP_ROLE_CHECK_SWITCH != (L2CAP_ROLE_CHECK_SWITCH & new_role)) {
   1211     /* do not process the allow_switch when both bits are set */
   1212     if (new_role & L2CAP_ROLE_ALLOW_SWITCH) {
   1213       l2cb.disallow_switch = false;
   1214     }
   1215     if (new_role & L2CAP_ROLE_DISALLOW_SWITCH) {
   1216       l2cb.disallow_switch = true;
   1217     }
   1218   }
   1219 
   1220   if (new_role == HCI_ROLE_MASTER || new_role == HCI_ROLE_SLAVE)
   1221     l2cb.desire_role = new_role;
   1222 
   1223   return (l2cb.desire_role);
   1224 }
   1225 
   1226 /*******************************************************************************
   1227  *
   1228  * Function     L2CA_LocalLoopbackReq
   1229  *
   1230  * Description  This function sets up a CID for local loopback
   1231  *
   1232  * Returns      CID of 0 if none.
   1233  *
   1234  ******************************************************************************/
   1235 uint16_t L2CA_LocalLoopbackReq(uint16_t psm, uint16_t handle,
   1236                                const RawAddress& p_bd_addr) {
   1237   tL2C_LCB* p_lcb;
   1238   tL2C_CCB* p_ccb;
   1239   tL2C_RCB* p_rcb;
   1240 
   1241   L2CAP_TRACE_API("L2CA_LocalLoopbackReq()  PSM: %d  Handle: 0x%04x", psm,
   1242                   handle);
   1243 
   1244   /* Fail if we have not established communications with the controller */
   1245   if (!BTM_IsDeviceUp()) {
   1246     L2CAP_TRACE_WARNING("L2CAP loop req - BTU not ready");
   1247     return (0);
   1248   }
   1249 
   1250   /* Fail if the PSM is not registered */
   1251   p_rcb = l2cu_find_rcb_by_psm(psm);
   1252   if (p_rcb == NULL) {
   1253     L2CAP_TRACE_WARNING("L2CAP - no RCB for L2CA_conn_req, PSM: %d", psm);
   1254     return (0);
   1255   }
   1256 
   1257   p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_BR_EDR);
   1258   if (p_lcb == NULL) {
   1259     L2CAP_TRACE_WARNING("L2CAP - no LCB for L2CA_conn_req");
   1260     return (0);
   1261   }
   1262 
   1263   p_lcb->link_state = LST_CONNECTED;
   1264   p_lcb->handle = handle;
   1265 
   1266   /* Allocate a channel control block */
   1267   p_ccb = l2cu_allocate_ccb(p_lcb, 0);
   1268   if (p_ccb == NULL) {
   1269     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_conn_req");
   1270     return (0);
   1271   }
   1272 
   1273   /* Save registration info */
   1274   p_ccb->p_rcb = p_rcb;
   1275   p_ccb->chnl_state = CST_OPEN;
   1276   p_ccb->remote_cid = p_ccb->local_cid;
   1277   p_ccb->config_done = CFG_DONE_MASK;
   1278 
   1279   /* Return the local CID as our handle */
   1280   return (p_ccb->local_cid);
   1281 }
   1282 
   1283 /*******************************************************************************
   1284  *
   1285  * Function         L2CA_SetAclPriority
   1286  *
   1287  * Description      Sets the transmission priority for a channel.
   1288  *                  (For initial implementation only two values are valid.
   1289  *                  L2CAP_PRIORITY_NORMAL and L2CAP_PRIORITY_HIGH).
   1290  *
   1291  * Returns          true if a valid channel, else false
   1292  *
   1293  ******************************************************************************/
   1294 bool L2CA_SetAclPriority(const RawAddress& bd_addr, uint8_t priority) {
   1295   VLOG(1) << __func__ << " BDA: " << bd_addr
   1296           << ", priority: " << std::to_string(priority);
   1297   return (l2cu_set_acl_priority(bd_addr, priority, false));
   1298 }
   1299 
   1300 /*******************************************************************************
   1301  *
   1302  * Function         L2CA_FlowControl
   1303  *
   1304  * Description      Higher layers call this function to flow control a channel.
   1305  *
   1306  *                  data_enabled - true data flows, false data is stopped
   1307  *
   1308  * Returns          true if valid channel, else false
   1309  *
   1310  ******************************************************************************/
   1311 bool L2CA_FlowControl(uint16_t cid, bool data_enabled) {
   1312   tL2C_CCB* p_ccb;
   1313   bool on_off = !data_enabled;
   1314 
   1315   L2CAP_TRACE_API("L2CA_FlowControl(%d)  CID: 0x%04x", on_off, cid);
   1316 
   1317   /* Find the channel control block. We don't know the link it is on. */
   1318   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
   1319   if (p_ccb == NULL) {
   1320     L2CAP_TRACE_WARNING(
   1321         "L2CAP - no CCB for L2CA_FlowControl, CID: 0x%04x  data_enabled: %d",
   1322         cid, data_enabled);
   1323     return (false);
   1324   }
   1325 
   1326   if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE) {
   1327     L2CAP_TRACE_EVENT("L2CA_FlowControl()  invalid mode:%d",
   1328                       p_ccb->peer_cfg.fcr.mode);
   1329     return (false);
   1330   }
   1331   if (p_ccb->fcrb.local_busy != on_off) {
   1332     p_ccb->fcrb.local_busy = on_off;
   1333 
   1334     if ((p_ccb->chnl_state == CST_OPEN) && (!p_ccb->fcrb.wait_ack)) {
   1335       if (on_off)
   1336         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
   1337       else
   1338         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_P_BIT);
   1339     }
   1340   }
   1341 
   1342   return (true);
   1343 }
   1344 
   1345 /*******************************************************************************
   1346  *
   1347  * Function         L2CA_SendTestSFrame
   1348  *
   1349  * Description      Higher layers call this function to send a test S-frame.
   1350  *
   1351  * Returns          true if valid Channel, else false
   1352  *
   1353  ******************************************************************************/
   1354 bool L2CA_SendTestSFrame(uint16_t cid, uint8_t sup_type, uint8_t back_track) {
   1355   tL2C_CCB* p_ccb;
   1356 
   1357   L2CAP_TRACE_API(
   1358       "L2CA_SendTestSFrame()  CID: 0x%04x  Type: 0x%02x  back_track: %u", cid,
   1359       sup_type, back_track);
   1360 
   1361   /* Find the channel control block. We don't know the link it is on. */
   1362   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
   1363   if (p_ccb == NULL) {
   1364     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_SendTestSFrame, CID: %d", cid);
   1365     return (false);
   1366   }
   1367 
   1368   if ((p_ccb->chnl_state != CST_OPEN) ||
   1369       (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE))
   1370     return (false);
   1371 
   1372   p_ccb->fcrb.next_seq_expected -= back_track;
   1373 
   1374   l2c_fcr_send_S_frame(
   1375       p_ccb, (uint16_t)(sup_type & 3),
   1376       (uint16_t)(sup_type & (L2CAP_FCR_P_BIT | L2CAP_FCR_F_BIT)));
   1377 
   1378   return (true);
   1379 }
   1380 
   1381 /*******************************************************************************
   1382  *
   1383  * Function         L2CA_SetTxPriority
   1384  *
   1385  * Description      Sets the transmission priority for a channel.
   1386  *
   1387  * Returns          true if a valid channel, else false
   1388  *
   1389  ******************************************************************************/
   1390 bool L2CA_SetTxPriority(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) {
   1391   tL2C_CCB* p_ccb;
   1392 
   1393   L2CAP_TRACE_API("L2CA_SetTxPriority()  CID: 0x%04x, priority:%d", cid,
   1394                   priority);
   1395 
   1396   /* Find the channel control block. We don't know the link it is on. */
   1397   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
   1398   if (p_ccb == NULL) {
   1399     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_SetTxPriority, CID: %d", cid);
   1400     return (false);
   1401   }
   1402 
   1403   /* it will update the order of CCB in LCB by priority and update round robin
   1404    * service variables */
   1405   l2cu_change_pri_ccb(p_ccb, priority);
   1406 
   1407   return (true);
   1408 }
   1409 
   1410 /*******************************************************************************
   1411  *
   1412  * Function         L2CA_SetChnlDataRate
   1413  *
   1414  * Description      Sets the tx/rx data rate for a channel.
   1415  *
   1416  * Returns          true if a valid channel, else false
   1417  *
   1418  ******************************************************************************/
   1419 bool L2CA_SetChnlDataRate(uint16_t cid, tL2CAP_CHNL_DATA_RATE tx,
   1420                           tL2CAP_CHNL_DATA_RATE rx) {
   1421   tL2C_CCB* p_ccb;
   1422 
   1423   L2CAP_TRACE_API("L2CA_SetChnlDataRate()  CID: 0x%04x, tx:%d, rx:%d", cid, tx,
   1424                   rx);
   1425 
   1426   /* Find the channel control block. We don't know the link it is on. */
   1427   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
   1428   if (p_ccb == NULL) {
   1429     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_SetChnlDataRate, CID: %d",
   1430                         cid);
   1431     return (false);
   1432   }
   1433 
   1434   p_ccb->tx_data_rate = tx;
   1435   p_ccb->rx_data_rate = rx;
   1436 
   1437   /* Adjust channel buffer allocation */
   1438   l2c_link_adjust_chnl_allocation();
   1439 
   1440   return (true);
   1441 }
   1442 
   1443 /*******************************************************************************
   1444  *
   1445  * Function         L2CA_SetFlushTimeout
   1446  *
   1447  * Description      This function set the automatic flush time out in Baseband
   1448  *                  for ACL-U packets.
   1449  *                  BdAddr : the remote BD address of ACL link. If it is
   1450  *                          BT_DB_ANY then the flush time out will be applied to
   1451  *                          all ACL links.
   1452  *                  FlushTimeout: flush time out in ms
   1453  *                           0x0000 : No automatic flush
   1454  *                           L2CAP_NO_RETRANSMISSION : No retransmission
   1455  *                           0x0002 - 0xFFFE : flush time out, if
   1456  *                                            (flush_tout * 8) + 3 / 5) <=
   1457  *                                             HCI_MAX_AUTOMATIC_FLUSH_TIMEOUT
   1458  *                                            (in 625us slot).
   1459  *                                    Otherwise, return false.
   1460  *                           L2CAP_NO_AUTOMATIC_FLUSH : No automatic flush
   1461  *
   1462  * Returns          true if command succeeded, false if failed
   1463  *
   1464  * NOTE             This flush timeout applies to all logical channels active on
   1465  *                  the ACL link.
   1466  ******************************************************************************/
   1467 bool L2CA_SetFlushTimeout(const RawAddress& bd_addr, uint16_t flush_tout) {
   1468   tL2C_LCB* p_lcb;
   1469   uint16_t hci_flush_to;
   1470   uint32_t temp;
   1471 
   1472   /* no automatic flush (infinite timeout) */
   1473   if (flush_tout == 0x0000) {
   1474     hci_flush_to = flush_tout;
   1475     flush_tout = L2CAP_NO_AUTOMATIC_FLUSH;
   1476   }
   1477   /* no retransmission */
   1478   else if (flush_tout == L2CAP_NO_RETRANSMISSION) {
   1479     /* not mandatory range for controller */
   1480     /* Packet is flushed before getting any ACK/NACK */
   1481     /* To do this, flush timeout should be 1 baseband slot */
   1482     hci_flush_to = flush_tout;
   1483   }
   1484   /* no automatic flush (infinite timeout) */
   1485   else if (flush_tout == L2CAP_NO_AUTOMATIC_FLUSH) {
   1486     hci_flush_to = 0x0000;
   1487   } else {
   1488     /* convert L2CAP flush_to to 0.625 ms units, with round */
   1489     temp = (((uint32_t)flush_tout * 8) + 3) / 5;
   1490 
   1491     /* if L2CAP flush_to within range of HCI, set HCI flush timeout */
   1492     if (temp > HCI_MAX_AUTOMATIC_FLUSH_TIMEOUT) {
   1493       L2CAP_TRACE_WARNING(
   1494           "WARNING L2CA_SetFlushTimeout timeout(0x%x) is out of range",
   1495           flush_tout);
   1496       return false;
   1497     } else {
   1498       hci_flush_to = (uint16_t)temp;
   1499     }
   1500   }
   1501 
   1502   if (RawAddress::kAny != bd_addr) {
   1503     p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
   1504 
   1505     if ((p_lcb) && (p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) {
   1506       if (p_lcb->link_flush_tout != flush_tout) {
   1507         p_lcb->link_flush_tout = flush_tout;
   1508 
   1509         VLOG(1) << __func__ << " BDA: " << bd_addr << " " << flush_tout << "ms";
   1510 
   1511         btsnd_hcic_write_auto_flush_tout(p_lcb->handle, hci_flush_to);
   1512       }
   1513     } else {
   1514       LOG(WARNING) << __func__ << " No lcb for bd_addr " << bd_addr;
   1515       return (false);
   1516     }
   1517   } else {
   1518     int xx;
   1519     p_lcb = &l2cb.lcb_pool[0];
   1520 
   1521     for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) {
   1522       if ((p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) {
   1523         if (p_lcb->link_flush_tout != flush_tout) {
   1524           p_lcb->link_flush_tout = flush_tout;
   1525 
   1526           VLOG(1) << __func__ << " BDA: " << p_lcb->remote_bd_addr << " "
   1527                   << flush_tout << "ms";
   1528 
   1529           btsnd_hcic_write_auto_flush_tout(p_lcb->handle, hci_flush_to);
   1530         }
   1531       }
   1532     }
   1533   }
   1534 
   1535   return (true);
   1536 }
   1537 
   1538 /*******************************************************************************
   1539  *
   1540  *  Function         L2CA_GetPeerFeatures
   1541  *
   1542  *  Description      Get a peers features and fixed channel map
   1543  *
   1544  *  Parameters:      BD address of the peer
   1545  *                   Pointers to features and channel mask storage area
   1546  *
   1547  *  Return value:    true if peer is connected
   1548  *
   1549  ******************************************************************************/
   1550 bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat,
   1551                           uint8_t* p_chnl_mask) {
   1552   tL2C_LCB* p_lcb;
   1553 
   1554   /* We must already have a link to the remote */
   1555   p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
   1556   if (p_lcb == NULL) {
   1557     LOG(WARNING) << __func__ << " No BDA: " << bd_addr;
   1558     return false;
   1559   }
   1560 
   1561   VLOG(1) << __func__ << " BDA: " << bd_addr
   1562           << StringPrintf(" ExtFea: 0x%08x Chnl_Mask[0]: 0x%02x",
   1563                           p_lcb->peer_ext_fea, p_lcb->peer_chnl_mask[0]);
   1564 
   1565   *p_ext_feat = p_lcb->peer_ext_fea;
   1566 
   1567   memcpy(p_chnl_mask, p_lcb->peer_chnl_mask, L2CAP_FIXED_CHNL_ARRAY_SIZE);
   1568 
   1569   return true;
   1570 }
   1571 
   1572 /*******************************************************************************
   1573  *
   1574  *  Function         L2CA_GetBDAddrbyHandle
   1575  *
   1576  *  Description      Get BD address for the given HCI handle
   1577  *
   1578  *  Parameters:      HCI handle
   1579  *                   BD address of the peer
   1580  *
   1581  *  Return value:    true if found lcb for the given handle, false otherwise
   1582  *
   1583  ******************************************************************************/
   1584 bool L2CA_GetBDAddrbyHandle(uint16_t handle, RawAddress& bd_addr) {
   1585   tL2C_LCB* p_lcb = NULL;
   1586   bool found_dev = false;
   1587 
   1588   p_lcb = l2cu_find_lcb_by_handle(handle);
   1589   if (p_lcb) {
   1590     found_dev = true;
   1591     bd_addr = p_lcb->remote_bd_addr;
   1592   }
   1593 
   1594   return found_dev;
   1595 }
   1596 
   1597 /*******************************************************************************
   1598  *
   1599  *  Function         L2CA_GetChnlFcrMode
   1600  *
   1601  *  Description      Get the channel FCR mode
   1602  *
   1603  *  Parameters:      Local CID
   1604  *
   1605  *  Return value:    Channel mode
   1606  *
   1607  ******************************************************************************/
   1608 uint8_t L2CA_GetChnlFcrMode(uint16_t lcid) {
   1609   tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
   1610 
   1611   if (p_ccb) {
   1612     L2CAP_TRACE_API("L2CA_GetChnlFcrMode() returns mode %d",
   1613                     p_ccb->peer_cfg.fcr.mode);
   1614     return (p_ccb->peer_cfg.fcr.mode);
   1615   }
   1616 
   1617   L2CAP_TRACE_API("L2CA_GetChnlFcrMode() returns mode L2CAP_FCR_BASIC_MODE");
   1618   return (L2CAP_FCR_BASIC_MODE);
   1619 }
   1620 
   1621 #if (L2CAP_NUM_FIXED_CHNLS > 0)
   1622 /*******************************************************************************
   1623  *
   1624  *  Function        L2CA_RegisterFixedChannel
   1625  *
   1626  *  Description     Register a fixed channel.
   1627  *
   1628  *  Parameters:     Fixed Channel #
   1629  *                  Channel Callbacks and config
   1630  *
   1631  *  Return value:   -
   1632  *
   1633  ******************************************************************************/
   1634 bool L2CA_RegisterFixedChannel(uint16_t fixed_cid,
   1635                                tL2CAP_FIXED_CHNL_REG* p_freg) {
   1636   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
   1637       (fixed_cid > L2CAP_LAST_FIXED_CHNL)) {
   1638     L2CAP_TRACE_ERROR("L2CA_RegisterFixedChannel()  Invalid CID: 0x%04x",
   1639                       fixed_cid);
   1640 
   1641     return (false);
   1642   }
   1643 
   1644   l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL] = *p_freg;
   1645   return (true);
   1646 }
   1647 
   1648 /*******************************************************************************
   1649  *
   1650  *  Function        L2CA_ConnectFixedChnl
   1651  *
   1652  *  Description     Connect an fixed signalling channel to a remote device.
   1653  *
   1654  *  Parameters:     Fixed CID
   1655  *                  BD Address of remote
   1656  *
   1657  *  Return value:   true if connection started
   1658  *
   1659  ******************************************************************************/
   1660 bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) {
   1661   uint8_t phy = controller_get_interface()->get_le_all_initiating_phys();
   1662   return L2CA_ConnectFixedChnl(fixed_cid, rem_bda, phy);
   1663 }
   1664 
   1665 bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda,
   1666                            uint8_t initiating_phys) {
   1667   tL2C_LCB* p_lcb;
   1668   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
   1669 
   1670   VLOG(1) << __func__ << " BDA: " << rem_bda
   1671           << StringPrintf("CID: 0x%04x ", fixed_cid);
   1672 
   1673   // Check CID is valid and registered
   1674   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
   1675       (fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
   1676       (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
   1677        NULL)) {
   1678     L2CAP_TRACE_ERROR("%s() Invalid CID: 0x%04x", __func__, fixed_cid);
   1679     return (false);
   1680   }
   1681 
   1682   // Fail if BT is not yet up
   1683   if (!BTM_IsDeviceUp()) {
   1684     L2CAP_TRACE_WARNING("%s(0x%04x) - BTU not ready", __func__, fixed_cid);
   1685     return (false);
   1686   }
   1687 
   1688   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
   1689     transport = BT_TRANSPORT_LE;
   1690 
   1691   tL2C_BLE_FIXED_CHNLS_MASK peer_channel_mask;
   1692 
   1693   // If we already have a link to the remote, check if it supports that CID
   1694   p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
   1695   if (p_lcb != NULL) {
   1696     // Fixed channels are mandatory on LE transports so ignore the received
   1697     // channel mask and use the locally cached LE channel mask.
   1698 
   1699     if (transport == BT_TRANSPORT_LE)
   1700       peer_channel_mask = l2cb.l2c_ble_fixed_chnls_mask;
   1701     else
   1702       peer_channel_mask = p_lcb->peer_chnl_mask[0];
   1703 
   1704     // Check for supported channel
   1705     if (!(peer_channel_mask & (1 << fixed_cid))) {
   1706       VLOG(2) << __func__ << " BDA " << rem_bda
   1707               << StringPrintf(" CID:0x%04x not supported", fixed_cid);
   1708       return false;
   1709     }
   1710 
   1711     // Get a CCB and link the lcb to it
   1712     if (!l2cu_initialize_fixed_ccb(
   1713             p_lcb, fixed_cid,
   1714             &l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL]
   1715                  .fixed_chnl_opts)) {
   1716       L2CAP_TRACE_WARNING("%s(0x%04x) - LCB but no CCB", __func__, fixed_cid);
   1717       return false;
   1718     }
   1719 
   1720     // racing with disconnecting, queue the connection request
   1721     if (p_lcb->link_state == LST_DISCONNECTING) {
   1722       L2CAP_TRACE_DEBUG("$s() - link disconnecting: RETRY LATER", __func__);
   1723       /* Save ccb so it can be started after disconnect is finished */
   1724       p_lcb->p_pending_ccb =
   1725           p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL];
   1726       return true;
   1727     }
   1728 
   1729     (*l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedConn_Cb)(
   1730         fixed_cid, p_lcb->remote_bd_addr, true, 0, p_lcb->transport);
   1731     return true;
   1732   }
   1733 
   1734   // No link. Get an LCB and start link establishment
   1735   p_lcb = l2cu_allocate_lcb(rem_bda, false, transport);
   1736   if (p_lcb == NULL) {
   1737     L2CAP_TRACE_WARNING("%s(0x%04x) - no LCB", __func__, fixed_cid);
   1738     return false;
   1739   }
   1740 
   1741   // Get a CCB and link the lcb to it
   1742   if (!l2cu_initialize_fixed_ccb(
   1743           p_lcb, fixed_cid, &l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL]
   1744                                  .fixed_chnl_opts)) {
   1745     p_lcb->disc_reason = L2CAP_CONN_NO_RESOURCES;
   1746     L2CAP_TRACE_WARNING("%s(0x%04x) - no CCB", __func__, fixed_cid);
   1747     l2cu_release_lcb(p_lcb);
   1748     return false;
   1749   }
   1750 
   1751   if (!l2cu_create_conn(p_lcb, transport, initiating_phys)) {
   1752     L2CAP_TRACE_WARNING("%s() - create_conn failed", __func__);
   1753     l2cu_release_lcb(p_lcb);
   1754     return false;
   1755   }
   1756   return true;
   1757 }
   1758 
   1759 /*******************************************************************************
   1760  *
   1761  *  Function        L2CA_SendFixedChnlData
   1762  *
   1763  *  Description     Write data on a fixed channel.
   1764  *
   1765  *  Parameters:     Fixed CID
   1766  *                  BD Address of remote
   1767  *                  Pointer to buffer of type BT_HDR
   1768  *
   1769  * Return value     L2CAP_DW_SUCCESS, if data accepted
   1770  *                  L2CAP_DW_FAILED,  if error
   1771  *
   1772  ******************************************************************************/
   1773 uint16_t L2CA_SendFixedChnlData(uint16_t fixed_cid, const RawAddress& rem_bda,
   1774                                 BT_HDR* p_buf) {
   1775   tL2C_LCB* p_lcb;
   1776   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
   1777 
   1778   VLOG(2) << __func__ << " BDA: " << rem_bda
   1779           << StringPrintf(" CID: 0x%04x", fixed_cid);
   1780 
   1781   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
   1782     transport = BT_TRANSPORT_LE;
   1783 
   1784   // Check CID is valid and registered
   1785   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
   1786       (fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
   1787       (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
   1788        NULL)) {
   1789     L2CAP_TRACE_ERROR("L2CA_SendFixedChnlData()  Invalid CID: 0x%04x",
   1790                       fixed_cid);
   1791     osi_free(p_buf);
   1792     return (L2CAP_DW_FAILED);
   1793   }
   1794 
   1795   // Fail if BT is not yet up
   1796   if (!BTM_IsDeviceUp()) {
   1797     L2CAP_TRACE_WARNING("L2CA_SendFixedChnlData(0x%04x) - BTU not ready",
   1798                         fixed_cid);
   1799     osi_free(p_buf);
   1800     return (L2CAP_DW_FAILED);
   1801   }
   1802 
   1803   // We need to have a link up
   1804   p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
   1805   if (p_lcb == NULL || p_lcb->link_state == LST_DISCONNECTING) {
   1806     /* if link is disconnecting, also report data sending failure */
   1807     L2CAP_TRACE_WARNING("L2CA_SendFixedChnlData(0x%04x) - no LCB", fixed_cid);
   1808     osi_free(p_buf);
   1809     return (L2CAP_DW_FAILED);
   1810   }
   1811 
   1812   tL2C_BLE_FIXED_CHNLS_MASK peer_channel_mask;
   1813 
   1814   // Select peer channels mask to use depending on transport
   1815   if (transport == BT_TRANSPORT_LE)
   1816     peer_channel_mask = l2cb.l2c_ble_fixed_chnls_mask;
   1817   else
   1818     peer_channel_mask = p_lcb->peer_chnl_mask[0];
   1819 
   1820   if ((peer_channel_mask & (1 << fixed_cid)) == 0) {
   1821     L2CAP_TRACE_WARNING(
   1822         "L2CA_SendFixedChnlData() - peer does not support fixed chnl: 0x%04x",
   1823         fixed_cid);
   1824     osi_free(p_buf);
   1825     return (L2CAP_DW_FAILED);
   1826   }
   1827 
   1828   p_buf->event = 0;
   1829   p_buf->layer_specific = L2CAP_FLUSHABLE_CH_BASED;
   1830 
   1831   if (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]) {
   1832     if (!l2cu_initialize_fixed_ccb(
   1833             p_lcb, fixed_cid,
   1834             &l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL]
   1835                  .fixed_chnl_opts)) {
   1836       L2CAP_TRACE_WARNING("L2CA_SendFixedChnlData() - no CCB for chnl: 0x%4x",
   1837                           fixed_cid);
   1838       osi_free(p_buf);
   1839       return (L2CAP_DW_FAILED);
   1840     }
   1841   }
   1842 
   1843   // If already congested, do not accept any more packets
   1844   if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent) {
   1845     L2CAP_TRACE_ERROR(
   1846         "L2CAP - CID: 0x%04x cannot send, already congested \
   1847             xmit_hold_q.count: %u buff_quota: %u",
   1848         fixed_cid, fixed_queue_length(
   1849                        p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]
   1850                            ->xmit_hold_q),
   1851         p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->buff_quota);
   1852     osi_free(p_buf);
   1853     return (L2CAP_DW_FAILED);
   1854   }
   1855 
   1856   l2c_enqueue_peer_data(p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL],
   1857                         p_buf);
   1858 
   1859   l2c_link_check_send_pkts(p_lcb, NULL, NULL);
   1860 
   1861   // If there is no dynamic CCB on the link, restart the idle timer each time
   1862   // something is sent
   1863   if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED &&
   1864       !p_lcb->ccb_queue.p_first_ccb) {
   1865     l2cu_no_dynamic_ccbs(p_lcb);
   1866   }
   1867 
   1868   if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent)
   1869     return (L2CAP_DW_CONGESTED);
   1870 
   1871   return (L2CAP_DW_SUCCESS);
   1872 }
   1873 
   1874 /*******************************************************************************
   1875  *
   1876  *  Function        L2CA_RemoveFixedChnl
   1877  *
   1878  *  Description     Remove a fixed channel to a remote device.
   1879  *
   1880  *  Parameters:     Fixed CID
   1881  *                  BD Address of remote
   1882  *                  Idle timeout to use (or 0xFFFF if don't care)
   1883  *
   1884  *  Return value:   true if channel removed
   1885  *
   1886  ******************************************************************************/
   1887 bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) {
   1888   tL2C_LCB* p_lcb;
   1889   tL2C_CCB* p_ccb;
   1890   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
   1891 
   1892   /* Check CID is valid and registered */
   1893   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
   1894       (fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
   1895       (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
   1896        NULL)) {
   1897     L2CAP_TRACE_ERROR("L2CA_RemoveFixedChnl()  Invalid CID: 0x%04x", fixed_cid);
   1898     return (false);
   1899   }
   1900 
   1901   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
   1902     transport = BT_TRANSPORT_LE;
   1903 
   1904   /* Is a fixed channel connected to the remote BDA ?*/
   1905   p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
   1906 
   1907   if (((p_lcb) == NULL) ||
   1908       (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL])) {
   1909     LOG(WARNING) << __func__ << " BDA: " << rem_bda
   1910                  << StringPrintf(" CID: 0x%04x not connected", fixed_cid);
   1911     return (false);
   1912   }
   1913 
   1914   VLOG(2) << __func__ << " BDA: " << rem_bda
   1915           << StringPrintf(" CID: 0x%04x", fixed_cid);
   1916 
   1917   /* Release the CCB, starting an inactivity timeout on the LCB if no other CCBs
   1918    * exist */
   1919   p_ccb = p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL];
   1920 
   1921   p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL] = NULL;
   1922   p_lcb->disc_reason = HCI_ERR_CONN_CAUSE_LOCAL_HOST;
   1923 
   1924   // Retain the link for a few more seconds after SMP pairing is done, since
   1925   // the Android platform always does service discovery after pairing is
   1926   // complete. This will avoid the link down (pairing is complete) and an
   1927   // immediate re-connection for service discovery.
   1928   // Some devices do not do auto advertising when link is dropped, thus fail
   1929   // the second connection and service discovery.
   1930   if ((fixed_cid == L2CAP_ATT_CID) && !p_lcb->ccb_queue.p_first_ccb)
   1931     p_lcb->idle_timeout = 0;
   1932 
   1933   l2cu_release_ccb(p_ccb);
   1934 
   1935   return (true);
   1936 }
   1937 
   1938 /*******************************************************************************
   1939  *
   1940  * Function         L2CA_SetFixedChannelTout
   1941  *
   1942  * Description      Higher layers call this function to set the idle timeout for
   1943  *                  a fixed channel. The "idle timeout" is the amount of time
   1944  *                  that a connection can remain up with no L2CAP channels on
   1945  *                  it. A timeout of zero means that the connection will be torn
   1946  *                  down immediately when the last channel is removed.
   1947  *                  A timeout of 0xFFFF means no timeout. Values are in seconds.
   1948  *                  A bd_addr is the remote BD address.
   1949  *
   1950  * Returns          true if command succeeded, false if failed
   1951  *
   1952  ******************************************************************************/
   1953 bool L2CA_SetFixedChannelTout(const RawAddress& rem_bda, uint16_t fixed_cid,
   1954                               uint16_t idle_tout) {
   1955   tL2C_LCB* p_lcb;
   1956   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
   1957 
   1958   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
   1959     transport = BT_TRANSPORT_LE;
   1960 
   1961   /* Is a fixed channel connected to the remote BDA ?*/
   1962   p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
   1963   if (((p_lcb) == NULL) ||
   1964       (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL])) {
   1965     LOG(WARNING) << __func__ << " BDA: " << rem_bda
   1966                  << StringPrintf(" CID: 0x%04x not connected", fixed_cid);
   1967     return (false);
   1968   }
   1969 
   1970   p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]
   1971       ->fixed_chnl_idle_tout = idle_tout;
   1972 
   1973   if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED &&
   1974       !p_lcb->ccb_queue.p_first_ccb) {
   1975     /* If there are no dynamic CCBs, (re)start the idle timer in case we changed
   1976      * it */
   1977     l2cu_no_dynamic_ccbs(p_lcb);
   1978   }
   1979 
   1980   return true;
   1981 }
   1982 
   1983 #endif /* #if (L2CAP_NUM_FIXED_CHNLS > 0) */
   1984 
   1985 /*******************************************************************************
   1986  *
   1987  * Function     L2CA_GetCurrentConfig
   1988  *
   1989  * Description  This function returns configurations of L2CAP channel
   1990  *              pp_our_cfg : pointer of our saved configuration options
   1991  *              p_our_cfg_bits : valid config in bitmap
   1992  *              pp_peer_cfg: pointer of peer's saved configuration options
   1993  *              p_peer_cfg_bits : valid config in bitmap
   1994  *
   1995  * Returns      true if successful
   1996  *
   1997  ******************************************************************************/
   1998 bool L2CA_GetCurrentConfig(uint16_t lcid, tL2CAP_CFG_INFO** pp_our_cfg,
   1999                            tL2CAP_CH_CFG_BITS* p_our_cfg_bits,
   2000                            tL2CAP_CFG_INFO** pp_peer_cfg,
   2001                            tL2CAP_CH_CFG_BITS* p_peer_cfg_bits) {
   2002   tL2C_CCB* p_ccb;
   2003 
   2004   L2CAP_TRACE_API("L2CA_GetCurrentConfig()  CID: 0x%04x", lcid);
   2005 
   2006   p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
   2007 
   2008   if (p_ccb) {
   2009     *pp_our_cfg = &(p_ccb->our_cfg);
   2010 
   2011     /* convert valid config items into bitmap */
   2012     *p_our_cfg_bits = 0;
   2013     if (p_ccb->our_cfg.mtu_present) *p_our_cfg_bits |= L2CAP_CH_CFG_MASK_MTU;
   2014     if (p_ccb->our_cfg.qos_present) *p_our_cfg_bits |= L2CAP_CH_CFG_MASK_QOS;
   2015     if (p_ccb->our_cfg.flush_to_present)
   2016       *p_our_cfg_bits |= L2CAP_CH_CFG_MASK_FLUSH_TO;
   2017     if (p_ccb->our_cfg.fcr_present) *p_our_cfg_bits |= L2CAP_CH_CFG_MASK_FCR;
   2018     if (p_ccb->our_cfg.fcs_present) *p_our_cfg_bits |= L2CAP_CH_CFG_MASK_FCS;
   2019     if (p_ccb->our_cfg.ext_flow_spec_present)
   2020       *p_our_cfg_bits |= L2CAP_CH_CFG_MASK_EXT_FLOW_SPEC;
   2021 
   2022     *pp_peer_cfg = &(p_ccb->peer_cfg);
   2023     *p_peer_cfg_bits = p_ccb->peer_cfg_bits;
   2024 
   2025     return true;
   2026   } else {
   2027     L2CAP_TRACE_ERROR("No CCB for CID:0x%04x", lcid);
   2028     return false;
   2029   }
   2030 }
   2031 
   2032 /*******************************************************************************
   2033  *
   2034  * Function      L2CA_GetConnectionConfig
   2035  *
   2036  * Description  This function returns configurations of L2CAP channel
   2037  *              pp_l2c_ccb : pointer to this channels L2CAP ccb data.
   2038  *
   2039  * Returns      true if successful
   2040  *
   2041  ******************************************************************************/
   2042 bool L2CA_GetConnectionConfig(uint16_t lcid, uint16_t* mtu, uint16_t* rcid,
   2043                               uint16_t* handle) {
   2044   tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
   2045   ;
   2046 
   2047   L2CAP_TRACE_API("%s CID: 0x%04x", __func__, lcid);
   2048 
   2049   if (p_ccb) {
   2050     *mtu = L2CAP_MTU_SIZE;
   2051     if (p_ccb->our_cfg.mtu_present) *mtu = p_ccb->our_cfg.mtu;
   2052 
   2053     *rcid = p_ccb->remote_cid;
   2054     *handle = p_ccb->p_lcb->handle;
   2055     return true;
   2056   }
   2057 
   2058   L2CAP_TRACE_ERROR("%s No CCB for CID:0x%04x", __func__, lcid);
   2059   return false;
   2060 }
   2061 
   2062 /*******************************************************************************
   2063  *
   2064  * Function         L2CA_RegForNoCPEvt
   2065  *
   2066  * Description      Register callback for Number of Completed Packets event.
   2067  *
   2068  * Input Param      p_cb - callback for Number of completed packets event
   2069  *                  p_bda - BT address of remote device
   2070  *
   2071  * Returns          true if registered OK, else false
   2072  *
   2073  ******************************************************************************/
   2074 bool L2CA_RegForNoCPEvt(tL2CA_NOCP_CB* p_cb, const RawAddress& p_bda) {
   2075   tL2C_LCB* p_lcb;
   2076 
   2077   /* Find the link that is associated with this remote bdaddr */
   2078   p_lcb = l2cu_find_lcb_by_bd_addr(p_bda, BT_TRANSPORT_BR_EDR);
   2079 
   2080   /* If no link for this handle, nothing to do. */
   2081   if (!p_lcb) return false;
   2082 
   2083   p_lcb->p_nocp_cb = p_cb;
   2084 
   2085   return true;
   2086 }
   2087 
   2088 /*******************************************************************************
   2089  *
   2090  * Function         L2CA_DataWrite
   2091  *
   2092  * Description      Higher layers call this function to write data.
   2093  *
   2094  * Returns          L2CAP_DW_SUCCESS, if data accepted, else false
   2095  *                  L2CAP_DW_CONGESTED, if data accepted and the channel is
   2096  *                                      congested
   2097  *                  L2CAP_DW_FAILED, if error
   2098  *
   2099  ******************************************************************************/
   2100 uint8_t L2CA_DataWrite(uint16_t cid, BT_HDR* p_data) {
   2101   L2CAP_TRACE_API("L2CA_DataWrite()  CID: 0x%04x  Len: %d", cid, p_data->len);
   2102   return l2c_data_write(cid, p_data, L2CAP_FLUSHABLE_CH_BASED);
   2103 }
   2104 
   2105 /*******************************************************************************
   2106  *
   2107  * Function         L2CA_SetChnlFlushability
   2108  *
   2109  * Description      Higher layers call this function to set a channels
   2110  *                  flushability flags
   2111  *
   2112  * Returns          true if CID found, else false
   2113  *
   2114  ******************************************************************************/
   2115 bool L2CA_SetChnlFlushability(uint16_t cid, bool is_flushable) {
   2116 #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE)
   2117 
   2118   tL2C_CCB* p_ccb;
   2119 
   2120   /* Find the channel control block. We don't know the link it is on. */
   2121   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
   2122   if (p_ccb == NULL) {
   2123     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_SetChnlFlushability, CID: %d",
   2124                         cid);
   2125     return (false);
   2126   }
   2127 
   2128   p_ccb->is_flushable = is_flushable;
   2129 
   2130   L2CAP_TRACE_API("L2CA_SetChnlFlushability()  CID: 0x%04x  is_flushable: %d",
   2131                   cid, is_flushable);
   2132 
   2133 #endif
   2134 
   2135   return (true);
   2136 }
   2137 
   2138 /*******************************************************************************
   2139  *
   2140  * Function         L2CA_DataWriteEx
   2141  *
   2142  * Description      Higher layers call this function to write data with extended
   2143  *                  flags.
   2144  *                  flags : L2CAP_FLUSHABLE_CH_BASED
   2145  *                          L2CAP_FLUSHABLE_PKT
   2146  *                          L2CAP_NON_FLUSHABLE_PKT
   2147  *
   2148  * Returns          L2CAP_DW_SUCCESS, if data accepted, else false
   2149  *                  L2CAP_DW_CONGESTED, if data accepted and the channel is
   2150  *                                      congested
   2151  *                  L2CAP_DW_FAILED, if error
   2152  *
   2153  ******************************************************************************/
   2154 uint8_t L2CA_DataWriteEx(uint16_t cid, BT_HDR* p_data, uint16_t flags) {
   2155   L2CAP_TRACE_API("L2CA_DataWriteEx()  CID: 0x%04x  Len: %d Flags:0x%04X", cid,
   2156                   p_data->len, flags);
   2157   return l2c_data_write(cid, p_data, flags);
   2158 }
   2159 
   2160 /*******************************************************************************
   2161  *
   2162  * Function     L2CA_FlushChannel
   2163  *
   2164  * Description  This function flushes none, some or all buffers queued up
   2165  *              for xmission for a particular CID. If called with
   2166  *              L2CAP_FLUSH_CHANS_GET (0), it simply returns the number
   2167  *              of buffers queued for that CID L2CAP_FLUSH_CHANS_ALL (0xffff)
   2168  *              flushes all buffers.  All other values specifies the maximum
   2169  *              buffers to flush.
   2170  *
   2171  * Returns      Number of buffers left queued for that CID
   2172  *
   2173  ******************************************************************************/
   2174 uint16_t L2CA_FlushChannel(uint16_t lcid, uint16_t num_to_flush) {
   2175   tL2C_CCB* p_ccb;
   2176   tL2C_LCB* p_lcb;
   2177   uint16_t num_left = 0, num_flushed1 = 0, num_flushed2 = 0;
   2178 
   2179   p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
   2180 
   2181   if (!p_ccb || (p_ccb->p_lcb == NULL)) {
   2182     L2CAP_TRACE_WARNING(
   2183         "L2CA_FlushChannel()  abnormally returning 0  CID: 0x%04x", lcid);
   2184     return (0);
   2185   }
   2186   p_lcb = p_ccb->p_lcb;
   2187 
   2188   if (num_to_flush != L2CAP_FLUSH_CHANS_GET) {
   2189     L2CAP_TRACE_API(
   2190         "L2CA_FlushChannel (FLUSH)  CID: 0x%04x  NumToFlush: %d  QC: %u  "
   2191         "pFirst: 0x%08x",
   2192         lcid, num_to_flush, fixed_queue_length(p_ccb->xmit_hold_q),
   2193         fixed_queue_try_peek_first(p_ccb->xmit_hold_q));
   2194   } else {
   2195     L2CAP_TRACE_API("L2CA_FlushChannel (QUERY)  CID: 0x%04x", lcid);
   2196   }
   2197 
   2198   /* Cannot flush eRTM buffers once they have a sequence number */
   2199   if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE) {
   2200 #if (L2CAP_NON_FLUSHABLE_PB_INCLUDED == TRUE)
   2201     if (num_to_flush != L2CAP_FLUSH_CHANS_GET) {
   2202       /* If the controller supports enhanced flush, flush the data queued at the
   2203        * controller */
   2204       if ((HCI_NON_FLUSHABLE_PB_SUPPORTED(BTM_ReadLocalFeatures())) &&
   2205           (BTM_GetNumScoLinks() == 0)) {
   2206         if (!l2cb.is_flush_active) {
   2207           l2cb.is_flush_active = true;
   2208 
   2209           /* The only packet type defined - 0 - Automatically-Flushable Only */
   2210           btsnd_hcic_enhanced_flush(p_lcb->handle, 0);
   2211         }
   2212       }
   2213     }
   2214 #endif
   2215 
   2216     // Iterate though list and flush the amount requested from
   2217     // the transmit data queue that satisfy the layer and event conditions.
   2218     for (const list_node_t* node = list_begin(p_lcb->link_xmit_data_q);
   2219          (num_to_flush > 0) && node != list_end(p_lcb->link_xmit_data_q);) {
   2220       BT_HDR* p_buf = (BT_HDR*)list_node(node);
   2221       node = list_next(node);
   2222       if ((p_buf->layer_specific == 0) && (p_buf->event == lcid)) {
   2223         num_to_flush--;
   2224         num_flushed1++;
   2225 
   2226         list_remove(p_lcb->link_xmit_data_q, p_buf);
   2227         osi_free(p_buf);
   2228       }
   2229     }
   2230   }
   2231 
   2232   /* If needed, flush buffers in the CCB xmit hold queue */
   2233   while ((num_to_flush != 0) && (!fixed_queue_is_empty(p_ccb->xmit_hold_q))) {
   2234     BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
   2235     osi_free(p_buf);
   2236     num_to_flush--;
   2237     num_flushed2++;
   2238   }
   2239 
   2240   /* If app needs to track all packets, call him */
   2241   if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) &&
   2242       (num_flushed2))
   2243     (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, num_flushed2);
   2244 
   2245   /* Now count how many are left */
   2246   for (const list_node_t* node = list_begin(p_lcb->link_xmit_data_q);
   2247        node != list_end(p_lcb->link_xmit_data_q); node = list_next(node)) {
   2248     BT_HDR* p_buf = (BT_HDR*)list_node(node);
   2249     if (p_buf->event == lcid) num_left++;
   2250   }
   2251 
   2252   /* Add in the number in the CCB xmit queue */
   2253   num_left += fixed_queue_length(p_ccb->xmit_hold_q);
   2254 
   2255   /* Return the local number of buffers left for the CID */
   2256   L2CAP_TRACE_DEBUG("L2CA_FlushChannel()  flushed: %u + %u,  num_left: %u",
   2257                     num_flushed1, num_flushed2, num_left);
   2258 
   2259   /* If we were congested, and now we are not, tell the app */
   2260   l2cu_check_channel_congestion(p_ccb);
   2261 
   2262   return (num_left);
   2263 }
   2264