OSDN Git Service

Add dumpsys support for LE connection parameter updates
[android-x86/system-bt.git] / stack / l2cap / l2c_ble.c
1 /******************************************************************************
2  *
3  *  Copyright (C) 2009-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 functions relating to BLE management.
22  *
23  ******************************************************************************/
24
25 #include <string.h>
26 #include "bt_target.h"
27 #include "bt_utils.h"
28 #include "l2cdefs.h"
29 #include "l2c_int.h"
30 #include "btu.h"
31 #include "btm_int.h"
32 #include "hcimsgs.h"
33 #include "device/include/controller.h"
34 #include "stack_config.h"
35 #include "btif_debug_l2c.h"
36
37 #if (BLE_INCLUDED == TRUE)
38
39 extern fixed_queue_t *btu_general_alarm_queue;
40
41 static void l2cble_start_conn_update (tL2C_LCB *p_lcb);
42
43 /*******************************************************************************
44 **
45 **  Function        L2CA_CancelBleConnectReq
46 **
47 **  Description     Cancel a pending connection attempt to a BLE device.
48 **
49 **  Parameters:     BD Address of remote
50 **
51 **  Return value:   TRUE if connection was cancelled
52 **
53 *******************************************************************************/
54 BOOLEAN L2CA_CancelBleConnectReq (BD_ADDR rem_bda)
55 {
56     tL2C_LCB *p_lcb;
57
58     /* There can be only one BLE connection request outstanding at a time */
59     if (btm_ble_get_conn_st() == BLE_CONN_IDLE)
60     {
61         L2CAP_TRACE_WARNING ("L2CA_CancelBleConnectReq - no connection pending");
62         return(FALSE);
63     }
64
65     if (memcmp (rem_bda, l2cb.ble_connecting_bda, BD_ADDR_LEN))
66     {
67         L2CAP_TRACE_WARNING ("L2CA_CancelBleConnectReq - different  BDA Connecting: %08x%04x  Cancel: %08x%04x",
68                               (l2cb.ble_connecting_bda[0]<<24)+(l2cb.ble_connecting_bda[1]<<16)+(l2cb.ble_connecting_bda[2]<<8)+l2cb.ble_connecting_bda[3],
69                               (l2cb.ble_connecting_bda[4]<<8)+l2cb.ble_connecting_bda[5],
70                               (rem_bda[0]<<24)+(rem_bda[1]<<16)+(rem_bda[2]<<8)+rem_bda[3], (rem_bda[4]<<8)+rem_bda[5]);
71
72         return(FALSE);
73     }
74
75     if (btsnd_hcic_ble_create_conn_cancel())
76     {
77         p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
78         /* Do not remove lcb if an LE link is already up as a peripheral */
79         if (p_lcb != NULL &&
80             !(p_lcb->link_role == HCI_ROLE_SLAVE && BTM_ACL_IS_CONNECTED(rem_bda)))
81         {
82             p_lcb->disc_reason = L2CAP_CONN_CANCEL;
83             l2cu_release_lcb (p_lcb);
84         }
85         /* update state to be cancel, wait for connection cancel complete */
86         btm_ble_set_conn_st (BLE_CONN_CANCEL);
87
88         return(TRUE);
89     }
90     else
91         return(FALSE);
92 }
93
94 /*******************************************************************************
95 **
96 **  Function        L2CA_UpdateBleConnParams
97 **
98 **  Description     Update BLE connection parameters.
99 **
100 **  Parameters:     BD Address of remote
101 **
102 **  Return value:   TRUE if update started
103 **
104 *******************************************************************************/
105 BOOLEAN L2CA_UpdateBleConnParams (BD_ADDR rem_bda, UINT16 min_int, UINT16 max_int,
106                                             UINT16 latency, UINT16 timeout)
107 {
108     tL2C_LCB            *p_lcb;
109     tACL_CONN           *p_acl_cb = btm_bda_to_acl(rem_bda, BT_TRANSPORT_LE);
110
111     /* See if we have a link control block for the remote device */
112     p_lcb = l2cu_find_lcb_by_bd_addr (rem_bda, BT_TRANSPORT_LE);
113
114     /* If we don't have one, create one and accept the connection. */
115     if (!p_lcb || !p_acl_cb)
116     {
117         L2CAP_TRACE_WARNING ("L2CA_UpdateBleConnParams - unknown BD_ADDR %08x%04x",
118                               (rem_bda[0]<<24)+(rem_bda[1]<<16)+(rem_bda[2]<<8)+rem_bda[3],
119                               (rem_bda[4]<<8)+rem_bda[5]);
120         return(FALSE);
121     }
122
123     if (p_lcb->transport != BT_TRANSPORT_LE)
124     {
125         L2CAP_TRACE_WARNING ("L2CA_UpdateBleConnParams - BD_ADDR %08x%04x not LE",
126                               (rem_bda[0]<<24)+(rem_bda[1]<<16)+(rem_bda[2]<<8)+rem_bda[3],
127                               (rem_bda[4]<<8)+rem_bda[5]);
128         return(FALSE);
129     }
130
131     p_lcb->min_interval = min_int;
132     p_lcb->max_interval = max_int;
133     p_lcb->latency = latency;
134     p_lcb->timeout = timeout;
135     p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
136
137     l2cble_start_conn_update(p_lcb);
138
139     return(TRUE);
140 }
141
142
143 /*******************************************************************************
144 **
145 **  Function        L2CA_EnableUpdateBleConnParams
146 **
147 **  Description     Enable or disable update based on the request from the peer
148 **
149 **  Parameters:     BD Address of remote
150 **
151 **  Return value:   TRUE if update started
152 **
153 *******************************************************************************/
154 BOOLEAN L2CA_EnableUpdateBleConnParams (BD_ADDR rem_bda, BOOLEAN enable)
155 {
156     if (stack_config_get_interface()->get_pts_conn_updates_disabled())
157         return false;
158
159     tL2C_LCB            *p_lcb;
160
161     /* See if we have a link control block for the remote device */
162     p_lcb = l2cu_find_lcb_by_bd_addr (rem_bda, BT_TRANSPORT_LE);
163
164     if (!p_lcb)
165     {
166         L2CAP_TRACE_WARNING ("L2CA_EnableUpdateBleConnParams - unknown BD_ADDR %08x%04x",
167             (rem_bda[0]<<24)+(rem_bda[1]<<16)+(rem_bda[2]<<8)+rem_bda[3],
168             (rem_bda[4]<<8)+rem_bda[5]);
169         return (FALSE);
170     }
171
172     L2CAP_TRACE_API ("%s - BD_ADDR %08x%04x enable %d current upd state 0x%02x",__FUNCTION__,
173         (rem_bda[0]<<24)+(rem_bda[1]<<16)+(rem_bda[2]<<8)+rem_bda[3],
174         (rem_bda[4]<<8)+rem_bda[5], enable, p_lcb->conn_update_mask);
175
176     if (p_lcb->transport != BT_TRANSPORT_LE)
177     {
178         L2CAP_TRACE_WARNING ("%s - BD_ADDR %08x%04x not LE (link role %d)", __FUNCTION__,
179                               (rem_bda[0]<<24)+(rem_bda[1]<<16)+(rem_bda[2]<<8)+rem_bda[3],
180                               (rem_bda[4]<<8)+rem_bda[5], p_lcb->link_role);
181         return (FALSE);
182     }
183
184     if (enable)
185         p_lcb->conn_update_mask &= ~L2C_BLE_CONN_UPDATE_DISABLE;
186     else
187         p_lcb->conn_update_mask |= L2C_BLE_CONN_UPDATE_DISABLE;
188
189     l2cble_start_conn_update(p_lcb);
190
191     return (TRUE);
192 }
193
194
195 /*******************************************************************************
196 **
197 ** Function         L2CA_GetBleConnRole
198 **
199 ** Description      This function returns the connection role.
200 **
201 ** Returns          link role.
202 **
203 *******************************************************************************/
204 UINT8 L2CA_GetBleConnRole (BD_ADDR bd_addr)
205 {
206     UINT8       role = HCI_ROLE_UNKNOWN;
207
208     tL2C_LCB *p_lcb;
209
210     if ((p_lcb = l2cu_find_lcb_by_bd_addr (bd_addr, BT_TRANSPORT_LE)) != NULL)
211         role = p_lcb->link_role;
212
213     return role;
214 }
215 /*******************************************************************************
216 **
217 ** Function         L2CA_GetDisconnectReason
218 **
219 ** Description      This function returns the disconnect reason code.
220 **
221 ** Returns          disconnect reason
222 **
223 *******************************************************************************/
224 UINT16 L2CA_GetDisconnectReason (BD_ADDR remote_bda, tBT_TRANSPORT transport)
225 {
226     tL2C_LCB            *p_lcb;
227     UINT16              reason = 0;
228
229     if ((p_lcb = l2cu_find_lcb_by_bd_addr (remote_bda, transport)) != NULL)
230         reason = p_lcb->disc_reason;
231
232     L2CAP_TRACE_DEBUG ("L2CA_GetDisconnectReason=%d ",reason);
233
234     return reason;
235 }
236
237 void l2cble_use_preferred_conn_params(BD_ADDR bda) {
238     tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr (bda, BT_TRANSPORT_LE);
239     tBTM_SEC_DEV_REC    *p_dev_rec = btm_find_or_alloc_dev (bda);
240
241     /* If there are any preferred connection parameters, set them now */
242     if ( (p_dev_rec->conn_params.min_conn_int     >= BTM_BLE_CONN_INT_MIN ) &&
243          (p_dev_rec->conn_params.min_conn_int     <= BTM_BLE_CONN_INT_MAX ) &&
244          (p_dev_rec->conn_params.max_conn_int     >= BTM_BLE_CONN_INT_MIN ) &&
245          (p_dev_rec->conn_params.max_conn_int     <= BTM_BLE_CONN_INT_MAX ) &&
246          (p_dev_rec->conn_params.slave_latency    <= BTM_BLE_CONN_LATENCY_MAX ) &&
247          (p_dev_rec->conn_params.supervision_tout >= BTM_BLE_CONN_SUP_TOUT_MIN) &&
248          (p_dev_rec->conn_params.supervision_tout <= BTM_BLE_CONN_SUP_TOUT_MAX) &&
249          ((p_lcb->min_interval < p_dev_rec->conn_params.min_conn_int &&
250           p_dev_rec->conn_params.min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ||
251           (p_lcb->min_interval > p_dev_rec->conn_params.max_conn_int) ||
252           (p_lcb->latency > p_dev_rec->conn_params.slave_latency) ||
253           (p_lcb->timeout > p_dev_rec->conn_params.supervision_tout)))
254     {
255         L2CAP_TRACE_DEBUG ("%s: HANDLE=%d min_conn_int=%d max_conn_int=%d slave_latency=%d supervision_tout=%d", __func__,
256                             p_lcb->handle, p_dev_rec->conn_params.min_conn_int, p_dev_rec->conn_params.max_conn_int,
257                             p_dev_rec->conn_params.slave_latency, p_dev_rec->conn_params.supervision_tout);
258
259         p_lcb->min_interval = p_dev_rec->conn_params.min_conn_int;
260         p_lcb->max_interval = p_dev_rec->conn_params.max_conn_int;
261         p_lcb->timeout      = p_dev_rec->conn_params.supervision_tout;
262         p_lcb->latency      = p_dev_rec->conn_params.slave_latency;
263
264         btsnd_hcic_ble_upd_ll_conn_params (p_lcb->handle,
265                                            p_dev_rec->conn_params.min_conn_int,
266                                            p_dev_rec->conn_params.max_conn_int,
267                                            p_dev_rec->conn_params.slave_latency,
268                                            p_dev_rec->conn_params.supervision_tout,
269                                            0, 0);
270     }
271 }
272
273 /*******************************************************************************
274 **
275 ** Function l2cble_notify_le_connection
276 **
277 ** Description This function notifiy the l2cap connection to the app layer
278 **
279 ** Returns none
280 **
281 *******************************************************************************/
282 void l2cble_notify_le_connection (BD_ADDR bda)
283 {
284     tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr (bda, BT_TRANSPORT_LE);
285     tACL_CONN *p_acl = btm_bda_to_acl(bda, BT_TRANSPORT_LE) ;
286     tL2C_CCB *p_ccb;
287
288     if (p_lcb != NULL && p_acl != NULL && p_lcb->link_state != LST_CONNECTED)
289     {
290         /* update link status */
291         btm_establish_continue(p_acl);
292         /* update l2cap link status and send callback */
293         p_lcb->link_state = LST_CONNECTED;
294         l2cu_process_fixed_chnl_resp (p_lcb);
295     }
296
297     /* For all channels, send the event through their FSMs */
298     for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb)
299     {
300         if (p_ccb->chnl_state == CST_CLOSED)
301             l2c_csm_execute (p_ccb, L2CEVT_LP_CONNECT_CFM, NULL);
302     }
303
304     l2cble_use_preferred_conn_params(bda);
305 }
306
307 /*******************************************************************************
308 **
309 ** Function         l2cble_scanner_conn_comp
310 **
311 ** Description      This function is called when an HCI Connection Complete
312 **                  event is received while we are a scanner (so we are master).
313 **
314 ** Returns          void
315 **
316 *******************************************************************************/
317 void l2cble_scanner_conn_comp (UINT16 handle, BD_ADDR bda, tBLE_ADDR_TYPE type,
318                                UINT16 conn_interval, UINT16 conn_latency, UINT16 conn_timeout)
319 {
320     tL2C_LCB            *p_lcb;
321     tBTM_SEC_DEV_REC    *p_dev_rec = btm_find_or_alloc_dev (bda);
322
323     L2CAP_TRACE_DEBUG ("l2cble_scanner_conn_comp: HANDLE=%d addr_type=%d conn_interval=%d slave_latency=%d supervision_tout=%d",
324                         handle,  type, conn_interval, conn_latency, conn_timeout);
325
326     l2cb.is_ble_connecting = FALSE;
327
328     /* See if we have a link control block for the remote device */
329     p_lcb = l2cu_find_lcb_by_bd_addr (bda, BT_TRANSPORT_LE);
330
331     /* If we don't have one, create one. this is auto connection complete. */
332     if (!p_lcb)
333     {
334         p_lcb = l2cu_allocate_lcb (bda, FALSE, BT_TRANSPORT_LE);
335         if (!p_lcb)
336         {
337             btm_sec_disconnect (handle, HCI_ERR_NO_CONNECTION);
338             L2CAP_TRACE_ERROR ("l2cble_scanner_conn_comp - failed to allocate LCB");
339             return;
340         }
341         else
342         {
343             if (!l2cu_initialize_fixed_ccb (p_lcb, L2CAP_ATT_CID, &l2cb.fixed_reg[L2CAP_ATT_CID - L2CAP_FIRST_FIXED_CHNL].fixed_chnl_opts))
344             {
345                 btm_sec_disconnect (handle, HCI_ERR_NO_CONNECTION);
346                 L2CAP_TRACE_WARNING ("l2cble_scanner_conn_comp - LCB but no CCB");
347                 return ;
348             }
349         }
350     }
351     else if (p_lcb->link_state != LST_CONNECTING)
352     {
353         L2CAP_TRACE_ERROR ("L2CAP got BLE scanner conn_comp in bad state: %d", p_lcb->link_state);
354         return;
355     }
356     alarm_cancel(p_lcb->l2c_lcb_timer);
357
358     /* Save the handle */
359     p_lcb->handle = handle;
360
361     /* Connected OK. Change state to connected, we were scanning so we are master */
362     p_lcb->link_role  = HCI_ROLE_MASTER;
363     p_lcb->transport  = BT_TRANSPORT_LE;
364
365     /* update link parameter, set slave link as non-spec default upon link up */
366     p_lcb->min_interval =  p_lcb->max_interval = conn_interval;
367     p_lcb->timeout      =  conn_timeout;
368     p_lcb->latency      =  conn_latency;
369     p_lcb->conn_update_mask = L2C_BLE_NOT_DEFAULT_PARAM;
370
371     /* Tell BTM Acl management about the link */
372     btm_acl_created (bda, NULL, p_dev_rec->sec_bd_name, handle, p_lcb->link_role, BT_TRANSPORT_LE);
373
374     p_lcb->peer_chnl_mask[0] = L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT;
375
376     btm_ble_set_conn_st(BLE_CONN_IDLE);
377
378 #if BLE_PRIVACY_SPT == TRUE
379     btm_ble_disable_resolving_list(BTM_BLE_RL_INIT, TRUE);
380 #endif
381 }
382
383
384 /*******************************************************************************
385 **
386 ** Function         l2cble_advertiser_conn_comp
387 **
388 ** Description      This function is called when an HCI Connection Complete
389 **                  event is received while we are an advertiser (so we are slave).
390 **
391 ** Returns          void
392 **
393 *******************************************************************************/
394 void l2cble_advertiser_conn_comp (UINT16 handle, BD_ADDR bda, tBLE_ADDR_TYPE type,
395                                   UINT16 conn_interval, UINT16 conn_latency, UINT16 conn_timeout)
396 {
397     tL2C_LCB            *p_lcb;
398     tBTM_SEC_DEV_REC    *p_dev_rec;
399     UNUSED(type);
400     UNUSED(conn_interval);
401     UNUSED(conn_latency);
402     UNUSED(conn_timeout);
403
404     /* See if we have a link control block for the remote device */
405     p_lcb = l2cu_find_lcb_by_bd_addr (bda, BT_TRANSPORT_LE);
406
407     /* If we don't have one, create one and accept the connection. */
408     if (!p_lcb)
409     {
410         p_lcb = l2cu_allocate_lcb (bda, FALSE, BT_TRANSPORT_LE);
411         if (!p_lcb)
412         {
413             btm_sec_disconnect (handle, HCI_ERR_NO_CONNECTION);
414             L2CAP_TRACE_ERROR ("l2cble_advertiser_conn_comp - failed to allocate LCB");
415             return;
416         }
417         else
418         {
419             if (!l2cu_initialize_fixed_ccb (p_lcb, L2CAP_ATT_CID, &l2cb.fixed_reg[L2CAP_ATT_CID - L2CAP_FIRST_FIXED_CHNL].fixed_chnl_opts))
420             {
421                 btm_sec_disconnect (handle, HCI_ERR_NO_CONNECTION);
422                 L2CAP_TRACE_WARNING ("l2cble_scanner_conn_comp - LCB but no CCB");
423                 return ;
424             }
425         }
426     }
427
428     /* Save the handle */
429     p_lcb->handle = handle;
430
431     /* Connected OK. Change state to connected, we were advertising, so we are slave */
432     p_lcb->link_role  = HCI_ROLE_SLAVE;
433     p_lcb->transport  = BT_TRANSPORT_LE;
434
435     /* update link parameter, set slave link as non-spec default upon link up */
436     p_lcb->min_interval = p_lcb->max_interval = conn_interval;
437     p_lcb->timeout      =  conn_timeout;
438     p_lcb->latency      =  conn_latency;
439     p_lcb->conn_update_mask = L2C_BLE_NOT_DEFAULT_PARAM;
440
441     /* Tell BTM Acl management about the link */
442     p_dev_rec = btm_find_or_alloc_dev (bda);
443
444     btm_acl_created (bda, NULL, p_dev_rec->sec_bd_name, handle, p_lcb->link_role, BT_TRANSPORT_LE);
445
446 #if BLE_PRIVACY_SPT == TRUE
447     btm_ble_disable_resolving_list(BTM_BLE_RL_ADV, TRUE);
448 #endif
449
450     p_lcb->peer_chnl_mask[0] = L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT;
451
452     if (!HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(controller_get_interface()->get_features_ble()->as_array))
453     {
454         p_lcb->link_state = LST_CONNECTED;
455         l2cu_process_fixed_chnl_resp (p_lcb);
456     }
457
458     /* when adv and initiating are both active, cancel the direct connection */
459     if (l2cb.is_ble_connecting && memcmp(bda, l2cb.ble_connecting_bda, BD_ADDR_LEN) == 0)
460     {
461         L2CA_CancelBleConnectReq(bda);
462     }
463 }
464
465 /*******************************************************************************
466 **
467 ** Function         l2cble_conn_comp
468 **
469 ** Description      This function is called when an HCI Connection Complete
470 **                  event is received.
471 **
472 ** Returns          void
473 **
474 *******************************************************************************/
475 void l2cble_conn_comp(UINT16 handle, UINT8 role, BD_ADDR bda, tBLE_ADDR_TYPE type,
476                       UINT16 conn_interval, UINT16 conn_latency, UINT16 conn_timeout)
477 {
478     btm_ble_update_link_topology_mask(role, TRUE);
479
480     if (role == HCI_ROLE_MASTER)
481     {
482         l2cble_scanner_conn_comp(handle, bda, type, conn_interval, conn_latency, conn_timeout);
483     }
484     else
485     {
486         l2cble_advertiser_conn_comp(handle, bda, type, conn_interval, conn_latency, conn_timeout);
487     }
488 }
489
490 /*******************************************************************************
491 **
492 **  Function        l2cble_start_conn_update
493 **
494 **  Description     start BLE connection parameter update process based on status
495 **
496 **  Parameters:     lcb : l2cap link control block
497 **
498 **  Return value:   none
499 **
500 *******************************************************************************/
501 static void l2cble_start_conn_update (tL2C_LCB *p_lcb)
502 {
503     UINT16 min_conn_int, max_conn_int, slave_latency, supervision_tout;
504     tACL_CONN *p_acl_cb = btm_bda_to_acl(p_lcb->remote_bd_addr, BT_TRANSPORT_LE);
505
506     // TODO(armansito): The return value of this call wasn't being used but the
507     // logic of this function might be depending on its side effects. We should
508     // verify if this call is needed at all and remove it otherwise.
509     btm_find_or_alloc_dev(p_lcb->remote_bd_addr);
510
511     if (p_lcb->conn_update_mask & L2C_BLE_UPDATE_PENDING) return;
512
513     if (p_lcb->conn_update_mask & L2C_BLE_CONN_UPDATE_DISABLE)
514     {
515         /* application requests to disable parameters update.
516            If parameters are already updated, lets set them
517            up to what has been requested during connection establishement */
518         if (p_lcb->conn_update_mask & L2C_BLE_NOT_DEFAULT_PARAM &&
519             /* current connection interval is greater than default min */
520             p_lcb->min_interval > BTM_BLE_CONN_INT_MIN)
521         {
522             /* use 7.5 ms as fast connection parameter, 0 slave latency */
523             min_conn_int = max_conn_int = BTM_BLE_CONN_INT_MIN;
524             slave_latency = BTM_BLE_CONN_SLAVE_LATENCY_DEF;
525             supervision_tout = BTM_BLE_CONN_TIMEOUT_DEF;
526
527             /* if both side 4.1, or we are master device, send HCI command */
528             if (p_lcb->link_role == HCI_ROLE_MASTER
529 #if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
530                 || (HCI_LE_CONN_PARAM_REQ_SUPPORTED(controller_get_interface()->get_features_ble()->as_array) &&
531                     HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl_cb->peer_le_features))
532 #endif
533                  )
534             {
535                 btsnd_hcic_ble_upd_ll_conn_params(p_lcb->handle, min_conn_int, max_conn_int,
536                                                   slave_latency, supervision_tout, 0, 0);
537                 p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING;
538             }
539             else
540             {
541                 l2cu_send_peer_ble_par_req (p_lcb, min_conn_int, max_conn_int, slave_latency, supervision_tout);
542             }
543             p_lcb->conn_update_mask &= ~L2C_BLE_NOT_DEFAULT_PARAM;
544             p_lcb->conn_update_mask |=  L2C_BLE_NEW_CONN_PARAM;
545          }
546     }
547     else
548     {
549         /* application allows to do update, if we were delaying one do it now */
550         if (p_lcb->conn_update_mask & L2C_BLE_NEW_CONN_PARAM)
551         {
552              /* if both side 4.1, or we are master device, send HCI command */
553             if (p_lcb->link_role == HCI_ROLE_MASTER
554 #if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
555                 || (HCI_LE_CONN_PARAM_REQ_SUPPORTED(controller_get_interface()->get_features_ble()->as_array) &&
556                     HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl_cb->peer_le_features))
557 #endif
558                  )
559             {
560                 btsnd_hcic_ble_upd_ll_conn_params(p_lcb->handle, p_lcb->min_interval,
561                     p_lcb->max_interval, p_lcb->latency, p_lcb->timeout, 0, 0);
562                 p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING;
563             }
564             else
565             {
566                 l2cu_send_peer_ble_par_req (p_lcb, p_lcb->min_interval, p_lcb->max_interval,
567                                             p_lcb->latency, p_lcb->timeout);
568             }
569             p_lcb->conn_update_mask &= ~L2C_BLE_NEW_CONN_PARAM;
570             p_lcb->conn_update_mask |= L2C_BLE_NOT_DEFAULT_PARAM;
571         }
572     }
573
574     /* Record the BLE connection update request. */
575     if (p_lcb->conn_update_mask & L2C_BLE_UPDATE_PENDING) {
576       bt_bdaddr_t bd_addr;
577       bdcpy(bd_addr.address, p_lcb->remote_bd_addr);
578       btif_debug_ble_connection_update_request(bd_addr, min_conn_int, max_conn_int, slave_latency,
579           supervision_tout);
580     }
581 }
582
583 /*******************************************************************************
584 **
585 ** Function         l2cble_process_conn_update_evt
586 **
587 ** Description      This function enables the connection update request from remote
588 **                  after a successful connection update response is received.
589 **
590 ** Returns          void
591 **
592 *******************************************************************************/
593 void l2cble_process_conn_update_evt (UINT16 handle, UINT8 status,
594                   UINT16 interval, UINT16 latency, UINT16 timeout)
595 {
596     L2CAP_TRACE_DEBUG("%s", __func__);
597
598     /* See if we have a link control block for the remote device */
599     tL2C_LCB *p_lcb = l2cu_find_lcb_by_handle(handle);
600     if (!p_lcb)
601     {
602         L2CAP_TRACE_WARNING("%s: Invalid handle: %d", __func__, handle);
603         return;
604     }
605
606     p_lcb->conn_update_mask &= ~L2C_BLE_UPDATE_PENDING;
607
608     if (status != HCI_SUCCESS)
609     {
610         L2CAP_TRACE_WARNING("%s: Error status: %d", __func__, status);
611     }
612
613     l2cble_start_conn_update(p_lcb);
614
615     /* Record the BLE connection update response. */
616     bt_bdaddr_t bd_addr;
617     bdcpy(bd_addr.address, p_lcb->remote_bd_addr);
618     btif_debug_ble_connection_update_response(bd_addr, status, interval,
619         latency, timeout);
620
621     L2CAP_TRACE_DEBUG("%s: conn_update_mask=%d", __func__, p_lcb->conn_update_mask);
622 }
623
624 /*******************************************************************************
625 **
626 ** Function         l2cble_process_sig_cmd
627 **
628 ** Description      This function is called when a signalling packet is received
629 **                  on the BLE signalling CID
630 **
631 ** Returns          void
632 **
633 *******************************************************************************/
634 void l2cble_process_sig_cmd (tL2C_LCB *p_lcb, UINT8 *p, UINT16 pkt_len)
635 {
636     UINT8           *p_pkt_end;
637     UINT8           cmd_code, id;
638     UINT16          cmd_len;
639     UINT16          min_interval, max_interval, latency, timeout;
640     tL2C_CONN_INFO  con_info;
641     UINT16          lcid = 0, rcid = 0, mtu = 0, mps = 0, initial_credit = 0;
642     tL2C_CCB        *p_ccb = NULL, *temp_p_ccb = NULL;
643     tL2C_RCB        *p_rcb;
644     UINT16          credit;
645     p_pkt_end = p + pkt_len;
646
647     STREAM_TO_UINT8  (cmd_code, p);
648     STREAM_TO_UINT8  (id, p);
649     STREAM_TO_UINT16 (cmd_len, p);
650
651     /* Check command length does not exceed packet length */
652     if ((p + cmd_len) > p_pkt_end)
653     {
654         L2CAP_TRACE_WARNING ("L2CAP - LE - format error, pkt_len: %d  cmd_len: %d  code: %d", pkt_len, cmd_len, cmd_code);
655         return;
656     }
657
658     switch (cmd_code)
659     {
660         case L2CAP_CMD_REJECT:
661             p += 2;
662             break;
663
664         case L2CAP_CMD_ECHO_REQ:
665         case L2CAP_CMD_ECHO_RSP:
666         case L2CAP_CMD_INFO_RSP:
667         case L2CAP_CMD_INFO_REQ:
668             l2cu_send_peer_cmd_reject (p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
669             break;
670
671         case L2CAP_CMD_BLE_UPDATE_REQ:
672             STREAM_TO_UINT16 (min_interval, p); /* 0x0006 - 0x0C80 */
673             STREAM_TO_UINT16 (max_interval, p); /* 0x0006 - 0x0C80 */
674             STREAM_TO_UINT16 (latency, p);  /* 0x0000 - 0x03E8 */
675             STREAM_TO_UINT16 (timeout, p);  /* 0x000A - 0x0C80 */
676             /* If we are a master, the slave wants to update the parameters */
677             if (p_lcb->link_role == HCI_ROLE_MASTER)
678             {
679                 if (min_interval < BTM_BLE_CONN_INT_MIN_LIMIT)
680                     min_interval = BTM_BLE_CONN_INT_MIN_LIMIT;
681
682                 if (min_interval < BTM_BLE_CONN_INT_MIN || min_interval > BTM_BLE_CONN_INT_MAX ||
683                     max_interval < BTM_BLE_CONN_INT_MIN || max_interval > BTM_BLE_CONN_INT_MAX ||
684                     latency  > BTM_BLE_CONN_LATENCY_MAX ||
685                     /*(timeout >= max_interval && latency > (timeout * 10/(max_interval * 1.25) - 1)) ||*/
686                     timeout < BTM_BLE_CONN_SUP_TOUT_MIN || timeout > BTM_BLE_CONN_SUP_TOUT_MAX ||
687                     max_interval < min_interval)
688                 {
689                     l2cu_send_peer_ble_par_rsp (p_lcb, L2CAP_CFG_UNACCEPTABLE_PARAMS, id);
690                 }
691                 else
692                 {
693
694                     l2cu_send_peer_ble_par_rsp (p_lcb, L2CAP_CFG_OK, id);
695
696                      p_lcb->min_interval = min_interval;
697                      p_lcb->max_interval = max_interval;
698                      p_lcb->latency = latency;
699                      p_lcb->timeout = timeout;
700                      p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
701
702                      l2cble_start_conn_update(p_lcb);
703                 }
704             }
705             else
706                 l2cu_send_peer_cmd_reject (p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
707             break;
708
709         case L2CAP_CMD_BLE_UPDATE_RSP:
710             p += 2;
711             break;
712
713         case L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ:
714             STREAM_TO_UINT16 (con_info.psm, p);
715             STREAM_TO_UINT16 (rcid, p);
716             STREAM_TO_UINT16 (mtu, p);
717             STREAM_TO_UINT16 (mps, p);
718             STREAM_TO_UINT16 (initial_credit, p);
719
720             L2CAP_TRACE_DEBUG ("Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_REQ with "
721                     "mtu = %d, "
722                     "mps = %d, "
723                     "initial credit = %d", mtu, mps, initial_credit);
724
725             if ((p_rcb = l2cu_find_ble_rcb_by_psm (con_info.psm)) == NULL)
726             {
727                 L2CAP_TRACE_WARNING ("L2CAP - rcvd conn req for unknown PSM: 0x%04x", con_info.psm);
728                 l2cu_reject_ble_connection (p_lcb, id, L2CAP_LE_NO_PSM);
729                 break;
730             }
731             else
732             {
733                 if (!p_rcb->api.pL2CA_ConnectInd_Cb)
734                 {
735                     L2CAP_TRACE_WARNING ("L2CAP - rcvd conn req for outgoing-only connection PSM: %d", con_info.psm);
736                     l2cu_reject_ble_connection (p_lcb, id, L2CAP_CONN_NO_PSM);
737                     break;
738                 }
739             }
740
741             /* Allocate a ccb for this.*/
742             if ((p_ccb = l2cu_allocate_ccb (p_lcb, 0)) == NULL)
743             {
744                 L2CAP_TRACE_ERROR ("L2CAP - unable to allocate CCB");
745                 l2cu_reject_ble_connection (p_lcb, id, L2CAP_CONN_NO_RESOURCES);
746                 break;
747             }
748
749             /* validate the parameters */
750             if (mtu < L2CAP_LE_MIN_MTU || mps < L2CAP_LE_MIN_MPS || mps > L2CAP_LE_MAX_MPS)
751             {
752                 L2CAP_TRACE_ERROR ("L2CAP don't like the params");
753                 l2cu_reject_ble_connection (p_lcb, id, L2CAP_CONN_NO_RESOURCES);
754                 break;
755             }
756
757             p_ccb->remote_id = id;
758             p_ccb->p_rcb = p_rcb;
759             p_ccb->remote_cid = rcid;
760
761             p_ccb->peer_conn_cfg.mtu = mtu;
762             p_ccb->peer_conn_cfg.mps = mps;
763             p_ccb->peer_conn_cfg.credits = initial_credit;
764
765             p_ccb->tx_mps = mps;
766             p_ccb->ble_sdu = NULL;
767             p_ccb->ble_sdu_length = 0;
768             p_ccb->is_first_seg = TRUE;
769             p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
770
771             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_REQ, &con_info);
772             break;
773
774         case L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES:
775             L2CAP_TRACE_DEBUG ("Recv L2CAP_CMD_BLE_CREDIT_BASED_CONN_RES");
776             /* For all channels, see whose identifier matches this id */
777             for (temp_p_ccb = p_lcb->ccb_queue.p_first_ccb; temp_p_ccb; temp_p_ccb = temp_p_ccb->p_next_ccb)
778             {
779                 if (temp_p_ccb->local_id == id)
780                 {
781                     p_ccb = temp_p_ccb;
782                     break;
783                 }
784             }
785             if (p_ccb)
786             {
787                 L2CAP_TRACE_DEBUG ("I remember the connection req");
788                 STREAM_TO_UINT16 (p_ccb->remote_cid, p);
789                 STREAM_TO_UINT16 (p_ccb->peer_conn_cfg.mtu, p);
790                 STREAM_TO_UINT16 (p_ccb->peer_conn_cfg.mps, p);
791                 STREAM_TO_UINT16 (p_ccb->peer_conn_cfg.credits, p);
792                 STREAM_TO_UINT16 (con_info.l2cap_result, p);
793                 con_info.remote_cid = p_ccb->remote_cid;
794
795                 L2CAP_TRACE_DEBUG ("remote_cid = %d, "
796                         "mtu = %d, "
797                         "mps = %d, "
798                         "initial_credit = %d, "
799                         "con_info.l2cap_result = %d",
800                         p_ccb->remote_cid, p_ccb->peer_conn_cfg.mtu, p_ccb->peer_conn_cfg.mps,
801                         p_ccb->peer_conn_cfg.credits, con_info.l2cap_result);
802
803                 /* validate the parameters */
804                 if (p_ccb->peer_conn_cfg.mtu < L2CAP_LE_MIN_MTU ||
805                         p_ccb->peer_conn_cfg.mps < L2CAP_LE_MIN_MPS ||
806                         p_ccb->peer_conn_cfg.mps > L2CAP_LE_MAX_MPS)
807                 {
808                     L2CAP_TRACE_ERROR ("L2CAP don't like the params");
809                     con_info.l2cap_result = L2CAP_LE_NO_RESOURCES;
810                     l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
811                     break;
812                 }
813
814                 p_ccb->tx_mps = p_ccb->peer_conn_cfg.mps;
815                 p_ccb->ble_sdu = NULL;
816                 p_ccb->ble_sdu_length = 0;
817                 p_ccb->is_first_seg = TRUE;
818                 p_ccb->peer_cfg.fcr.mode = L2CAP_FCR_LE_COC_MODE;
819
820                 if (con_info.l2cap_result == L2CAP_LE_CONN_OK)
821                     l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP, &con_info);
822                 else
823                     l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
824             }
825             else
826             {
827                 L2CAP_TRACE_DEBUG ("I DO NOT remember the connection req");
828                 con_info.l2cap_result = L2CAP_LE_INVALID_SOURCE_CID;
829                 l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
830             }
831             break;
832
833         case L2CAP_CMD_BLE_FLOW_CTRL_CREDIT:
834             STREAM_TO_UINT16(lcid, p);
835             if((p_ccb = l2cu_find_ccb_by_remote_cid(p_lcb, lcid)) == NULL)
836             {
837                 L2CAP_TRACE_DEBUG ("%s Credit received for unknown channel id %d", __func__, lcid);
838                 break;
839             }
840
841             STREAM_TO_UINT16(credit ,p);
842             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT, &credit);
843             L2CAP_TRACE_DEBUG ("%s Credit received", __func__);
844             break;
845
846         case L2CAP_CMD_DISC_REQ:
847             STREAM_TO_UINT16 (lcid, p);
848             STREAM_TO_UINT16 (rcid, p);
849
850             if ((p_ccb = l2cu_find_ccb_by_cid (p_lcb, lcid)) != NULL)
851             {
852                 if (p_ccb->remote_cid == rcid)
853                 {
854                     p_ccb->remote_id = id;
855                     l2c_csm_execute (p_ccb, L2CEVT_L2CAP_DISCONNECT_REQ, NULL);
856                 }
857             }
858             else
859                 l2cu_send_peer_disc_rsp (p_lcb, id, lcid, rcid);
860
861             break;
862
863          case L2CAP_CMD_DISC_RSP:
864             STREAM_TO_UINT16 (rcid, p);
865             STREAM_TO_UINT16 (lcid, p);
866
867             if ((p_ccb = l2cu_find_ccb_by_cid (p_lcb, lcid)) != NULL)
868             {
869                 if ((p_ccb->remote_cid == rcid) && (p_ccb->local_id == id))
870                     l2c_csm_execute (p_ccb, L2CEVT_L2CAP_DISCONNECT_RSP, NULL);
871             }
872             break;
873
874         default:
875             L2CAP_TRACE_WARNING ("L2CAP - LE - unknown cmd code: %d", cmd_code);
876             l2cu_send_peer_cmd_reject (p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
877             break;
878     }
879 }
880
881 /*******************************************************************************
882 **
883 ** Function         l2cble_init_direct_conn
884 **
885 ** Description      This function is to initate a direct connection
886 **
887 ** Returns          TRUE connection initiated, FALSE otherwise.
888 **
889 *******************************************************************************/
890 BOOLEAN l2cble_init_direct_conn (tL2C_LCB *p_lcb)
891 {
892     tBTM_SEC_DEV_REC *p_dev_rec = btm_find_or_alloc_dev (p_lcb->remote_bd_addr);
893     tBTM_BLE_CB *p_cb = &btm_cb.ble_ctr_cb;
894     UINT16 scan_int;
895     UINT16 scan_win;
896     BD_ADDR peer_addr;
897     UINT8 peer_addr_type = BLE_ADDR_PUBLIC;
898     UINT8 own_addr_type = BLE_ADDR_PUBLIC;
899
900     /* There can be only one BLE connection request outstanding at a time */
901     if (p_dev_rec == NULL)
902     {
903         L2CAP_TRACE_WARNING ("unknown device, can not initate connection");
904         return(FALSE);
905     }
906
907     scan_int = (p_cb->scan_int == BTM_BLE_SCAN_PARAM_UNDEF) ? BTM_BLE_SCAN_FAST_INT : p_cb->scan_int;
908     scan_win = (p_cb->scan_win == BTM_BLE_SCAN_PARAM_UNDEF) ? BTM_BLE_SCAN_FAST_WIN : p_cb->scan_win;
909
910     peer_addr_type = p_lcb->ble_addr_type;
911     memcpy(peer_addr, p_lcb->remote_bd_addr, BD_ADDR_LEN);
912
913 #if ( (defined BLE_PRIVACY_SPT) && (BLE_PRIVACY_SPT == TRUE))
914     own_addr_type = btm_cb.ble_ctr_cb.privacy_mode ? BLE_ADDR_RANDOM : BLE_ADDR_PUBLIC;
915     if (p_dev_rec->ble.in_controller_list & BTM_RESOLVING_LIST_BIT)
916     {
917         if (btm_cb.ble_ctr_cb.privacy_mode >=  BTM_PRIVACY_1_2)
918             own_addr_type |= BLE_ADDR_TYPE_ID_BIT;
919
920         btm_ble_enable_resolving_list(BTM_BLE_RL_INIT);
921         btm_random_pseudo_to_identity_addr(peer_addr, &peer_addr_type);
922     } else {
923         btm_ble_disable_resolving_list(BTM_BLE_RL_INIT, TRUE);
924
925         // If we have a current RPA, use that instead.
926         if (!bdaddr_is_empty((const bt_bdaddr_t *)p_dev_rec->ble.cur_rand_addr)) {
927             memcpy(peer_addr, p_dev_rec->ble.cur_rand_addr, BD_ADDR_LEN);
928         }
929     }
930 #endif
931
932     if (!btm_ble_topology_check(BTM_BLE_STATE_INIT))
933     {
934         l2cu_release_lcb (p_lcb);
935         L2CAP_TRACE_ERROR("initate direct connection fail, topology limitation");
936         return FALSE;
937     }
938
939     if (!btsnd_hcic_ble_create_ll_conn (scan_int,/* UINT16 scan_int      */
940                                         scan_win, /* UINT16 scan_win      */
941                                         FALSE,                   /* UINT8 white_list     */
942                                         peer_addr_type,          /* UINT8 addr_type_peer */
943                                         peer_addr,               /* BD_ADDR bda_peer     */
944                                         own_addr_type,         /* UINT8 addr_type_own  */
945         (UINT16) ((p_dev_rec->conn_params.min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ?
946         p_dev_rec->conn_params.min_conn_int : BTM_BLE_CONN_INT_MIN_DEF),  /* UINT16 conn_int_min  */
947         (UINT16) ((p_dev_rec->conn_params.max_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ?
948         p_dev_rec->conn_params.max_conn_int : BTM_BLE_CONN_INT_MAX_DEF),  /* UINT16 conn_int_max  */
949         (UINT16) ((p_dev_rec->conn_params.slave_latency != BTM_BLE_CONN_PARAM_UNDEF) ?
950         p_dev_rec->conn_params.slave_latency : BTM_BLE_CONN_SLAVE_LATENCY_DEF), /* UINT16 conn_latency  */
951         (UINT16) ((p_dev_rec->conn_params.supervision_tout != BTM_BLE_CONN_PARAM_UNDEF) ?
952         p_dev_rec->conn_params.supervision_tout : BTM_BLE_CONN_TIMEOUT_DEF), /* conn_timeout */
953                                         0,                       /* UINT16 min_len       */
954                                         0))                      /* UINT16 max_len       */
955     {
956         l2cu_release_lcb (p_lcb);
957         L2CAP_TRACE_ERROR("initate direct connection fail, no resources");
958         return (FALSE);
959     }
960     else
961     {
962         p_lcb->link_state = LST_CONNECTING;
963         l2cb.is_ble_connecting = TRUE;
964         memcpy (l2cb.ble_connecting_bda, p_lcb->remote_bd_addr, BD_ADDR_LEN);
965         alarm_set_on_queue(p_lcb->l2c_lcb_timer,
966                            L2CAP_BLE_LINK_CONNECT_TIMEOUT_MS,
967                            l2c_lcb_timer_timeout, p_lcb,
968                            btu_general_alarm_queue);
969         btm_ble_set_conn_st (BLE_DIR_CONN);
970
971         return (TRUE);
972     }
973 }
974
975 /*******************************************************************************
976 **
977 ** Function         l2cble_create_conn
978 **
979 ** Description      This function initiates an acl connection via HCI
980 **
981 ** Returns          TRUE if successful, FALSE if connection not started.
982 **
983 *******************************************************************************/
984 BOOLEAN l2cble_create_conn (tL2C_LCB *p_lcb)
985 {
986     tBTM_BLE_CONN_ST     conn_st = btm_ble_get_conn_st();
987     BOOLEAN         rt = FALSE;
988
989     /* There can be only one BLE connection request outstanding at a time */
990     if (conn_st == BLE_CONN_IDLE)
991     {
992         rt = l2cble_init_direct_conn(p_lcb);
993     }
994     else
995     {
996         L2CAP_TRACE_WARNING ("L2CAP - LE - cannot start new connection at conn st: %d", conn_st);
997
998         btm_ble_enqueue_direct_conn_req(p_lcb);
999
1000         if (conn_st == BLE_BG_CONN)
1001             btm_ble_suspend_bg_conn();
1002
1003         rt = TRUE;
1004     }
1005     return rt;
1006 }
1007
1008 /*******************************************************************************
1009 **
1010 ** Function         l2c_link_processs_ble_num_bufs
1011 **
1012 ** Description      This function is called when a "controller buffer size"
1013 **                  event is first received from the controller. It updates
1014 **                  the L2CAP values.
1015 **
1016 ** Returns          void
1017 **
1018 *******************************************************************************/
1019 void l2c_link_processs_ble_num_bufs (UINT16 num_lm_ble_bufs)
1020 {
1021     if (num_lm_ble_bufs == 0)
1022     {
1023         num_lm_ble_bufs = L2C_DEF_NUM_BLE_BUF_SHARED;
1024         l2cb.num_lm_acl_bufs -= L2C_DEF_NUM_BLE_BUF_SHARED;
1025     }
1026
1027     l2cb.num_lm_ble_bufs = l2cb.controller_le_xmit_window = num_lm_ble_bufs;
1028 }
1029
1030 /*******************************************************************************
1031 **
1032 ** Function         l2c_ble_link_adjust_allocation
1033 **
1034 ** Description      This function is called when a link is created or removed
1035 **                  to calculate the amount of packets each link may send to
1036 **                  the HCI without an ack coming back.
1037 **
1038 **                  Currently, this is a simple allocation, dividing the
1039 **                  number of Controller Packets by the number of links. In
1040 **                  the future, QOS configuration should be examined.
1041 **
1042 ** Returns          void
1043 **
1044 *******************************************************************************/
1045 void l2c_ble_link_adjust_allocation (void)
1046 {
1047     UINT16      qq, yy, qq_remainder;
1048     tL2C_LCB    *p_lcb;
1049     UINT16      hi_quota, low_quota;
1050     UINT16      num_lowpri_links = 0;
1051     UINT16      num_hipri_links  = 0;
1052     UINT16      controller_xmit_quota = l2cb.num_lm_ble_bufs;
1053     UINT16      high_pri_link_quota = L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A;
1054
1055     /* If no links active, reset buffer quotas and controller buffers */
1056     if (l2cb.num_ble_links_active == 0)
1057     {
1058         l2cb.controller_le_xmit_window = l2cb.num_lm_ble_bufs;
1059         l2cb.ble_round_robin_quota = l2cb.ble_round_robin_unacked = 0;
1060         return;
1061     }
1062
1063     /* First, count the links */
1064     for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++)
1065     {
1066         if (p_lcb->in_use && p_lcb->transport == BT_TRANSPORT_LE)
1067         {
1068             if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)
1069                 num_hipri_links++;
1070             else
1071                 num_lowpri_links++;
1072         }
1073     }
1074
1075     /* now adjust high priority link quota */
1076     low_quota = num_lowpri_links ? 1 : 0;
1077     while ( (num_hipri_links * high_pri_link_quota + low_quota) > controller_xmit_quota )
1078         high_pri_link_quota--;
1079
1080
1081     /* Work out the xmit quota and buffer quota high and low priorities */
1082     hi_quota  = num_hipri_links * high_pri_link_quota;
1083     low_quota = (hi_quota < controller_xmit_quota) ? controller_xmit_quota - hi_quota : 1;
1084
1085     /* Work out and save the HCI xmit quota for each low priority link */
1086
1087     /* If each low priority link cannot have at least one buffer */
1088     if (num_lowpri_links > low_quota)
1089     {
1090         l2cb.ble_round_robin_quota = low_quota;
1091         qq = qq_remainder = 0;
1092     }
1093     /* If each low priority link can have at least one buffer */
1094     else if (num_lowpri_links > 0)
1095     {
1096         l2cb.ble_round_robin_quota = 0;
1097         l2cb.ble_round_robin_unacked = 0;
1098         qq = low_quota / num_lowpri_links;
1099         qq_remainder = low_quota % num_lowpri_links;
1100     }
1101     /* If no low priority link */
1102     else
1103     {
1104         l2cb.ble_round_robin_quota = 0;
1105         l2cb.ble_round_robin_unacked = 0;
1106         qq = qq_remainder = 0;
1107     }
1108     L2CAP_TRACE_EVENT ("l2c_ble_link_adjust_allocation  num_hipri: %u  num_lowpri: %u  low_quota: %u  round_robin_quota: %u  qq: %u",
1109                         num_hipri_links, num_lowpri_links, low_quota,
1110                         l2cb.ble_round_robin_quota, qq);
1111
1112     /* Now, assign the quotas to each link */
1113     for (yy = 0, p_lcb = &l2cb.lcb_pool[0]; yy < MAX_L2CAP_LINKS; yy++, p_lcb++)
1114     {
1115         if (p_lcb->in_use && p_lcb->transport == BT_TRANSPORT_LE)
1116         {
1117             if (p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)
1118             {
1119                 p_lcb->link_xmit_quota   = high_pri_link_quota;
1120             }
1121             else
1122             {
1123                 /* Safety check in case we switched to round-robin with something outstanding */
1124                 /* if sent_not_acked is added into round_robin_unacked then don't add it again */
1125                 /* l2cap keeps updating sent_not_acked for exiting from round robin */
1126                 if (( p_lcb->link_xmit_quota > 0 )&&( qq == 0 ))
1127                     l2cb.ble_round_robin_unacked += p_lcb->sent_not_acked;
1128
1129                 p_lcb->link_xmit_quota   = qq;
1130                 if (qq_remainder > 0)
1131                 {
1132                     p_lcb->link_xmit_quota++;
1133                     qq_remainder--;
1134                 }
1135             }
1136
1137             L2CAP_TRACE_EVENT("l2c_ble_link_adjust_allocation LCB %d   Priority: %d  XmitQuota: %d",
1138                                 yy, p_lcb->acl_priority, p_lcb->link_xmit_quota);
1139
1140             L2CAP_TRACE_EVENT("        SentNotAcked: %d  RRUnacked: %d",
1141                                 p_lcb->sent_not_acked, l2cb.round_robin_unacked);
1142
1143             /* There is a special case where we have readjusted the link quotas and  */
1144             /* this link may have sent anything but some other link sent packets so  */
1145             /* so we may need a timer to kick off this link's transmissions.         */
1146             if ( (p_lcb->link_state == LST_CONNECTED)
1147               && (!list_is_empty(p_lcb->link_xmit_data_q))
1148                  && (p_lcb->sent_not_acked < p_lcb->link_xmit_quota) ) {
1149                 alarm_set_on_queue(p_lcb->l2c_lcb_timer,
1150                                    L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS,
1151                                    l2c_lcb_timer_timeout, p_lcb,
1152                                    btu_general_alarm_queue);
1153             }
1154         }
1155     }
1156 }
1157
1158 #if (defined BLE_LLT_INCLUDED) && (BLE_LLT_INCLUDED == TRUE)
1159 /*******************************************************************************
1160 **
1161 ** Function         l2cble_process_rc_param_request_evt
1162 **
1163 ** Description      process LE Remote Connection Parameter Request Event.
1164 **
1165 ** Returns          void
1166 **
1167 *******************************************************************************/
1168 void l2cble_process_rc_param_request_evt(UINT16 handle, UINT16 int_min, UINT16 int_max,
1169                                      UINT16 latency, UINT16 timeout)
1170 {
1171     tL2C_LCB    *p_lcb = l2cu_find_lcb_by_handle (handle);
1172
1173     if (p_lcb != NULL)
1174     {
1175         p_lcb->min_interval = int_min;
1176         p_lcb->max_interval = int_max;
1177         p_lcb->latency = latency;
1178         p_lcb->timeout = timeout;
1179
1180         /* if update is enabled, always accept connection parameter update */
1181         if ((p_lcb->conn_update_mask & L2C_BLE_CONN_UPDATE_DISABLE) == 0)
1182         {
1183             btsnd_hcic_ble_rc_param_req_reply(handle, int_min, int_max, latency, timeout, 0, 0);
1184         }
1185         else
1186         {
1187             L2CAP_TRACE_EVENT ("L2CAP - LE - update currently disabled");
1188             p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM;
1189             btsnd_hcic_ble_rc_param_req_neg_reply (handle,HCI_ERR_UNACCEPT_CONN_INTERVAL);
1190         }
1191
1192     }
1193     else
1194     {
1195         L2CAP_TRACE_WARNING("No link to update connection parameter")
1196     }
1197 }
1198 #endif
1199
1200 /*******************************************************************************
1201 **
1202 ** Function         l2cble_update_data_length
1203 **
1204 ** Description      This function update link tx data length if applicable
1205 **
1206 ** Returns          void
1207 **
1208 *******************************************************************************/
1209 void l2cble_update_data_length(tL2C_LCB *p_lcb)
1210 {
1211     UINT16 tx_mtu = 0;
1212     UINT16 i = 0;
1213
1214     L2CAP_TRACE_DEBUG("%s", __FUNCTION__);
1215
1216     /* See if we have a link control block for the connection */
1217     if (p_lcb == NULL)
1218         return;
1219
1220     for (i = 0; i < L2CAP_NUM_FIXED_CHNLS; i++)
1221     {
1222         if (i + L2CAP_FIRST_FIXED_CHNL != L2CAP_BLE_SIGNALLING_CID)
1223         {
1224             if ((p_lcb->p_fixed_ccbs[i] != NULL) &&
1225                     (tx_mtu < (p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD)))
1226                 tx_mtu = p_lcb->p_fixed_ccbs[i]->tx_data_len + L2CAP_PKT_OVERHEAD;
1227         }
1228     }
1229
1230     if (tx_mtu > BTM_BLE_DATA_SIZE_MAX)
1231         tx_mtu = BTM_BLE_DATA_SIZE_MAX;
1232
1233     /* update TX data length if changed */
1234     if (p_lcb->tx_data_len != tx_mtu)
1235         BTM_SetBleDataLength(p_lcb->remote_bd_addr, tx_mtu);
1236
1237 }
1238
1239 /*******************************************************************************
1240 **
1241 ** Function         l2cble_process_data_length_change_evt
1242 **
1243 ** Description      This function process the data length change event
1244 **
1245 ** Returns          void
1246 **
1247 *******************************************************************************/
1248 void l2cble_process_data_length_change_event(UINT16 handle, UINT16 tx_data_len, UINT16 rx_data_len)
1249 {
1250     tL2C_LCB *p_lcb = l2cu_find_lcb_by_handle(handle);
1251
1252     L2CAP_TRACE_DEBUG("%s TX data len = %d", __FUNCTION__, tx_data_len);
1253     if (p_lcb == NULL)
1254         return;
1255
1256     if (tx_data_len > 0)
1257         p_lcb->tx_data_len = tx_data_len;
1258
1259     /* ignore rx_data len for now */
1260 }
1261
1262 /*******************************************************************************
1263 **
1264 ** Function         l2cble_set_fixed_channel_tx_data_length
1265 **
1266 ** Description      This function update max fixed channel tx data length if applicable
1267 **
1268 ** Returns          void
1269 **
1270 *******************************************************************************/
1271 void l2cble_set_fixed_channel_tx_data_length(BD_ADDR remote_bda, UINT16 fix_cid, UINT16 tx_mtu)
1272 {
1273     tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr(remote_bda, BT_TRANSPORT_LE);
1274     UINT16 cid = fix_cid - L2CAP_FIRST_FIXED_CHNL;
1275
1276     L2CAP_TRACE_DEBUG("%s TX MTU = %d", __FUNCTION__, tx_mtu);
1277
1278     if (!controller_get_interface()->supports_ble_packet_extension())
1279     {
1280         L2CAP_TRACE_WARNING("%s, request not supported", __FUNCTION__);
1281         return;
1282     }
1283
1284     /* See if we have a link control block for the connection */
1285     if (p_lcb == NULL)
1286         return;
1287
1288     if (p_lcb->p_fixed_ccbs[cid] != NULL)
1289     {
1290         if (tx_mtu > BTM_BLE_DATA_SIZE_MAX)
1291             tx_mtu = BTM_BLE_DATA_SIZE_MAX;
1292
1293         p_lcb->p_fixed_ccbs[cid]->tx_data_len = tx_mtu;
1294     }
1295
1296     l2cble_update_data_length(p_lcb);
1297 }
1298
1299 /*******************************************************************************
1300 **
1301 ** Function         l2cble_credit_based_conn_req
1302 **
1303 ** Description      This function sends LE Credit Based Connection Request for
1304 **                  LE connection oriented channels.
1305 **
1306 ** Returns          void
1307 **
1308 *******************************************************************************/
1309 void l2cble_credit_based_conn_req (tL2C_CCB *p_ccb)
1310 {
1311     if (!p_ccb)
1312         return;
1313
1314     if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
1315     {
1316         L2CAP_TRACE_WARNING ("LE link doesn't exist");
1317         return;
1318     }
1319
1320     l2cu_send_peer_ble_credit_based_conn_req (p_ccb);
1321     return;
1322 }
1323
1324 /*******************************************************************************
1325 **
1326 ** Function         l2cble_credit_based_conn_res
1327 **
1328 ** Description      This function sends LE Credit Based Connection Response for
1329 **                  LE connection oriented channels.
1330 **
1331 ** Returns          void
1332 **
1333 *******************************************************************************/
1334 void l2cble_credit_based_conn_res (tL2C_CCB *p_ccb, UINT16 result)
1335 {
1336     if (!p_ccb)
1337         return;
1338
1339     if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
1340     {
1341         L2CAP_TRACE_WARNING ("LE link doesn't exist");
1342         return;
1343     }
1344
1345     l2cu_send_peer_ble_credit_based_conn_res (p_ccb, result);
1346     return;
1347 }
1348
1349 /*******************************************************************************
1350 **
1351 ** Function         l2cble_send_flow_control_credit
1352 **
1353 ** Description      This function sends flow control credits for
1354 **                  LE connection oriented channels.
1355 **
1356 ** Returns          void
1357 **
1358 *******************************************************************************/
1359 void l2cble_send_flow_control_credit(tL2C_CCB *p_ccb, UINT16 credit_value)
1360 {
1361     if (!p_ccb)
1362         return;
1363
1364     if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
1365     {
1366         L2CAP_TRACE_WARNING ("LE link doesn't exist");
1367         return;
1368     }
1369
1370     l2cu_send_peer_ble_flow_control_credit(p_ccb, credit_value);
1371     return;
1372
1373 }
1374
1375 /*******************************************************************************
1376 **
1377 ** Function         l2cble_send_peer_disc_req
1378 **
1379 ** Description      This function sends disconnect request
1380 **                  to the peer LE device
1381 **
1382 ** Returns          void
1383 **
1384 *******************************************************************************/
1385 void l2cble_send_peer_disc_req(tL2C_CCB *p_ccb)
1386 {
1387     L2CAP_TRACE_DEBUG ("%s",__func__);
1388     if (!p_ccb)
1389         return;
1390
1391     if (p_ccb->p_lcb && p_ccb->p_lcb->transport != BT_TRANSPORT_LE)
1392     {
1393         L2CAP_TRACE_WARNING ("LE link doesn't exist");
1394         return;
1395     }
1396
1397     l2cu_send_peer_ble_credit_based_disconn_req(p_ccb);
1398     return;
1399 }
1400
1401 /*******************************************************************************
1402 **
1403 ** Function         l2cble_sec_comp
1404 **
1405 ** Description      This function is called when security procedure for an LE COC
1406 **                  link is done
1407 **
1408 ** Returns          void
1409 **
1410 *******************************************************************************/
1411 void  l2cble_sec_comp(BD_ADDR p_bda, tBT_TRANSPORT transport, void *p_ref_data, UINT8 status)
1412 {
1413     tL2C_LCB *p_lcb = l2cu_find_lcb_by_bd_addr(p_bda, BT_TRANSPORT_LE);
1414     tL2CAP_SEC_DATA *p_buf = NULL;
1415     UINT8 sec_flag;
1416     UINT8 sec_act;
1417
1418     if (!p_lcb)
1419     {
1420         L2CAP_TRACE_WARNING ("%s security complete for unknown device", __func__);
1421         return;
1422     }
1423
1424     sec_act = p_lcb->sec_act;
1425     p_lcb->sec_act = 0;
1426
1427     if (!fixed_queue_is_empty(p_lcb->le_sec_pending_q))
1428     {
1429         p_buf = (tL2CAP_SEC_DATA*) fixed_queue_dequeue(p_lcb->le_sec_pending_q);
1430         if (!p_buf)
1431         {
1432             L2CAP_TRACE_WARNING ("%s Security complete for request not initiated from L2CAP",
1433                     __func__);
1434             return;
1435         }
1436
1437         if (status != BTM_SUCCESS)
1438         {
1439             (*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
1440         }
1441         else
1442         {
1443             if (sec_act == BTM_SEC_ENCRYPT_MITM)
1444             {
1445                 BTM_GetSecurityFlagsByTransport(p_bda, &sec_flag, transport);
1446                 if (sec_flag & BTM_SEC_FLAG_LKEY_AUTHED)
1447                     (*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
1448                 else
1449                 {
1450                     L2CAP_TRACE_DEBUG ("%s MITM Protection Not present", __func__);
1451                     (*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data,
1452                             BTM_FAILED_ON_SECURITY);
1453                 }
1454             }
1455             else
1456             {
1457                 L2CAP_TRACE_DEBUG ("%s MITM Protection not required sec_act = %d",
1458                         __func__, p_lcb->sec_act);
1459
1460                 (*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
1461             }
1462         }
1463     }
1464     else
1465     {
1466         L2CAP_TRACE_WARNING ("%s Security complete for request not initiated from L2CAP", __func__);
1467         return;
1468     }
1469     osi_free(p_buf);
1470
1471     while (!fixed_queue_is_empty(p_lcb->le_sec_pending_q))
1472     {
1473         p_buf = (tL2CAP_SEC_DATA*) fixed_queue_dequeue(p_lcb->le_sec_pending_q);
1474
1475         if (status != BTM_SUCCESS)
1476             (*(p_buf->p_callback))(p_bda, BT_TRANSPORT_LE, p_buf->p_ref_data, status);
1477         else
1478             l2ble_sec_access_req(p_bda, p_buf->psm, p_buf->is_originator,
1479                     p_buf->p_callback, p_buf->p_ref_data);
1480
1481        osi_free(p_buf);
1482     }
1483 }
1484
1485 /*******************************************************************************
1486 **
1487 ** Function         l2ble_sec_access_req
1488 **
1489 ** Description      This function is called by LE COC link to meet the
1490 **                  security requirement for the link
1491 **
1492 ** Returns          TRUE - security procedures are started
1493 **                  FALSE - failure
1494 **
1495 *******************************************************************************/
1496 BOOLEAN l2ble_sec_access_req(BD_ADDR bd_addr, UINT16 psm, BOOLEAN is_originator, tL2CAP_SEC_CBACK *p_callback, void *p_ref_data)
1497 {
1498     L2CAP_TRACE_DEBUG ("%s", __func__);
1499     BOOLEAN status;
1500     tL2C_LCB *p_lcb = NULL;
1501
1502     if (!p_callback)
1503     {
1504         L2CAP_TRACE_ERROR("%s No callback function", __func__);
1505         return FALSE;
1506     }
1507
1508     p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_LE);
1509
1510     if (!p_lcb)
1511     {
1512         L2CAP_TRACE_ERROR ("%s Security check for unknown device", __func__);
1513         p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_UNKNOWN_ADDR);
1514         return FALSE;
1515     }
1516
1517     tL2CAP_SEC_DATA *p_buf = (tL2CAP_SEC_DATA*) osi_malloc((UINT16)sizeof(tL2CAP_SEC_DATA));
1518     if (!p_buf)
1519     {
1520         p_callback(bd_addr, BT_TRANSPORT_LE, p_ref_data, BTM_NO_RESOURCES);
1521         return FALSE;
1522     }
1523
1524     p_buf->psm = psm;
1525     p_buf->is_originator = is_originator;
1526     p_buf->p_callback = p_callback;
1527     p_buf->p_ref_data = p_ref_data;
1528     fixed_queue_enqueue(p_lcb->le_sec_pending_q, p_buf);
1529     status = btm_ble_start_sec_check(bd_addr, psm, is_originator, &l2cble_sec_comp, p_ref_data);
1530
1531     return status;
1532 }
1533 #endif /* (BLE_INCLUDED == TRUE) */