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