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