OSDN Git Service

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