OSDN Git Service

Merge "Fix potential OOB write in btm_read_remote_ext_features_complete" into oc...
[android-x86/system-bt.git] / stack / btm / btm_acl.cc
1 /******************************************************************************
2  *
3  *  Copyright (C) 2000-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  *  Name:          btm_acl.cc
22  *
23  *  Description:   This file contains functions that handle ACL connections.
24  *                 This includes operations such as hold and sniff modes,
25  *                 supported packet types.
26  *
27  *                 This module contains both internal and external (API)
28  *                 functions. External (API) functions are distinguishable
29  *                 by their names beginning with uppercase BTM.
30  *
31  *
32  *****************************************************************************/
33
34 #include <stddef.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38
39 #include "bt_common.h"
40 #include "bt_target.h"
41 #include "bt_types.h"
42 #include "bt_utils.h"
43 #include "btm_api.h"
44 #include "btm_int.h"
45 #include "btu.h"
46 #include "device/include/controller.h"
47 #include "device/include/interop.h"
48 #include "hcidefs.h"
49 #include "hcimsgs.h"
50 #include "log/log.h"
51 #include "l2c_int.h"
52 #include "osi/include/osi.h"
53
54 extern fixed_queue_t* btu_general_alarm_queue;
55
56 static void btm_read_remote_features(uint16_t handle);
57 static void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number);
58 static void btm_process_remote_ext_features(tACL_CONN* p_acl_cb,
59                                             uint8_t num_read_pages);
60
61 /* 3 seconds timeout waiting for responses */
62 #define BTM_DEV_REPLY_TIMEOUT_MS (3 * 1000)
63
64 /*******************************************************************************
65  *
66  * Function         btm_acl_init
67  *
68  * Description      This function is called at BTM startup to initialize
69  *
70  * Returns          void
71  *
72  ******************************************************************************/
73 void btm_acl_init(void) {
74   BTM_TRACE_DEBUG("btm_acl_init");
75   /* Initialize nonzero defaults */
76   btm_cb.btm_def_link_super_tout = HCI_DEFAULT_INACT_TOUT;
77   btm_cb.acl_disc_reason = 0xff;
78 }
79
80 /*******************************************************************************
81  *
82  * Function        btm_bda_to_acl
83  *
84  * Description     This function returns the FIRST acl_db entry for the passed
85  *                 BDA.
86  *
87  * Parameters      bda : BD address of the remote device
88  *                 transport : Physical transport used for ACL connection
89  *                 (BR/EDR or LE)
90  *
91  * Returns         Returns pointer to the ACL DB for the requested BDA if found.
92  *                 NULL if not found.
93  *
94  ******************************************************************************/
95 tACL_CONN* btm_bda_to_acl(const BD_ADDR bda, tBT_TRANSPORT transport) {
96   tACL_CONN* p = &btm_cb.acl_db[0];
97   uint16_t xx;
98   if (bda) {
99     for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
100       if ((p->in_use) && (!memcmp(p->remote_addr, bda, BD_ADDR_LEN)) &&
101           p->transport == transport) {
102         BTM_TRACE_DEBUG("btm_bda_to_acl found");
103         return (p);
104       }
105     }
106   }
107
108   /* If here, no BD Addr found */
109   return ((tACL_CONN*)NULL);
110 }
111
112 /*******************************************************************************
113  *
114  * Function         btm_handle_to_acl_index
115  *
116  * Description      This function returns the FIRST acl_db entry for the passed
117  *                  hci_handle.
118  *
119  * Returns          index to the acl_db or MAX_L2CAP_LINKS.
120  *
121  ******************************************************************************/
122 uint8_t btm_handle_to_acl_index(uint16_t hci_handle) {
123   tACL_CONN* p = &btm_cb.acl_db[0];
124   uint8_t xx;
125   BTM_TRACE_DEBUG("btm_handle_to_acl_index");
126   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
127     if ((p->in_use) && (p->hci_handle == hci_handle)) {
128       break;
129     }
130   }
131
132   /* If here, no BD Addr found */
133   return (xx);
134 }
135
136 #if (BLE_PRIVACY_SPT == TRUE)
137 /*******************************************************************************
138  *
139  * Function         btm_ble_get_acl_remote_addr
140  *
141  * Description      This function reads the active remote address used for the
142  *                  connection.
143  *
144  * Returns          success return true, otherwise false.
145  *
146  ******************************************************************************/
147 bool btm_ble_get_acl_remote_addr(tBTM_SEC_DEV_REC* p_dev_rec, BD_ADDR conn_addr,
148                                  tBLE_ADDR_TYPE* p_addr_type) {
149   bool st = true;
150
151   if (p_dev_rec == NULL) {
152     BTM_TRACE_ERROR(
153         "btm_ble_get_acl_remote_addr can not find device with matching "
154         "address");
155     return false;
156   }
157
158   switch (p_dev_rec->ble.active_addr_type) {
159     case BTM_BLE_ADDR_PSEUDO:
160       memcpy(conn_addr, p_dev_rec->bd_addr, BD_ADDR_LEN);
161       *p_addr_type = p_dev_rec->ble.ble_addr_type;
162       break;
163
164     case BTM_BLE_ADDR_RRA:
165       memcpy(conn_addr, p_dev_rec->ble.cur_rand_addr, BD_ADDR_LEN);
166       *p_addr_type = BLE_ADDR_RANDOM;
167       break;
168
169     case BTM_BLE_ADDR_STATIC:
170       memcpy(conn_addr, p_dev_rec->ble.static_addr, BD_ADDR_LEN);
171       *p_addr_type = p_dev_rec->ble.static_addr_type;
172       break;
173
174     default:
175       BTM_TRACE_ERROR("Unknown active address: %d",
176                       p_dev_rec->ble.active_addr_type);
177       st = false;
178       break;
179   }
180
181   return st;
182 }
183 #endif
184 /*******************************************************************************
185  *
186  * Function         btm_acl_created
187  *
188  * Description      This function is called by L2CAP when an ACL connection
189  *                  is created.
190  *
191  * Returns          void
192  *
193  ******************************************************************************/
194 void btm_acl_created(BD_ADDR bda, DEV_CLASS dc, BD_NAME bdn,
195                      uint16_t hci_handle, uint8_t link_role,
196                      tBT_TRANSPORT transport) {
197   tBTM_SEC_DEV_REC* p_dev_rec = NULL;
198   tACL_CONN* p;
199   uint8_t xx;
200
201   BTM_TRACE_DEBUG("btm_acl_created hci_handle=%d link_role=%d  transport=%d",
202                   hci_handle, link_role, transport);
203   /* Ensure we don't have duplicates */
204   p = btm_bda_to_acl(bda, transport);
205   if (p != (tACL_CONN*)NULL) {
206     p->hci_handle = hci_handle;
207     p->link_role = link_role;
208     p->transport = transport;
209     BTM_TRACE_DEBUG(
210         "Duplicate btm_acl_created: RemBdAddr: %02x%02x%02x%02x%02x%02x",
211         bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
212     BTM_SetLinkPolicy(p->remote_addr, &btm_cb.btm_def_link_policy);
213     return;
214   }
215
216   /* Allocate acl_db entry */
217   for (xx = 0, p = &btm_cb.acl_db[0]; xx < MAX_L2CAP_LINKS; xx++, p++) {
218     if (!p->in_use) {
219       p->in_use = true;
220       p->hci_handle = hci_handle;
221       p->link_role = link_role;
222       p->link_up_issued = false;
223       memcpy(p->remote_addr, bda, BD_ADDR_LEN);
224
225       p->transport = transport;
226 #if (BLE_PRIVACY_SPT == TRUE)
227       if (transport == BT_TRANSPORT_LE)
228         btm_ble_refresh_local_resolvable_private_addr(
229             bda, btm_cb.ble_ctr_cb.addr_mgnt_cb.private_addr);
230 #else
231       p->conn_addr_type = BLE_ADDR_PUBLIC;
232       memcpy(p->conn_addr, &controller_get_interface()->get_address()->address,
233              BD_ADDR_LEN);
234
235 #endif
236       p->switch_role_failed_attempts = 0;
237       p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
238
239       btm_pm_sm_alloc(xx);
240
241       if (dc) memcpy(p->remote_dc, dc, DEV_CLASS_LEN);
242
243       if (bdn) memcpy(p->remote_name, bdn, BTM_MAX_REM_BD_NAME_LEN);
244
245       /* if BR/EDR do something more */
246       if (transport == BT_TRANSPORT_BR_EDR) {
247         btsnd_hcic_read_rmt_clk_offset(p->hci_handle);
248         btsnd_hcic_rmt_ver_req(p->hci_handle);
249       }
250       p_dev_rec = btm_find_dev_by_handle(hci_handle);
251
252       if (p_dev_rec) {
253         BTM_TRACE_DEBUG("device_type=0x%x", p_dev_rec->device_type);
254       }
255
256       if (p_dev_rec && !(transport == BT_TRANSPORT_LE)) {
257         /* If remote features already known, copy them and continue connection
258          * setup */
259         if ((p_dev_rec->num_read_pages) &&
260             (p_dev_rec->num_read_pages <= (HCI_EXT_FEATURES_PAGE_MAX + 1))) {
261           memcpy(p->peer_lmp_feature_pages, p_dev_rec->feature_pages,
262                  (HCI_FEATURE_BYTES_PER_PAGE * p_dev_rec->num_read_pages));
263           p->num_read_pages = p_dev_rec->num_read_pages;
264
265           const uint8_t req_pend = (p_dev_rec->sm4 & BTM_SM4_REQ_PEND);
266
267           /* Store the Peer Security Capabilites (in SM4 and rmt_sec_caps) */
268           btm_sec_set_peer_sec_caps(p, p_dev_rec);
269
270           BTM_TRACE_API("%s: pend:%d", __func__, req_pend);
271           if (req_pend) {
272             /* Request for remaining Security Features (if any) */
273             l2cu_resubmit_pending_sec_req(p_dev_rec->bd_addr);
274           }
275           btm_establish_continue(p);
276           return;
277         }
278       }
279
280       /* If here, features are not known yet */
281       if (p_dev_rec && transport == BT_TRANSPORT_LE) {
282 #if (BLE_PRIVACY_SPT == TRUE)
283         btm_ble_get_acl_remote_addr(p_dev_rec, p->active_remote_addr,
284                                     &p->active_remote_addr_type);
285 #endif
286
287         if (HCI_LE_SLAVE_INIT_FEAT_EXC_SUPPORTED(
288                 controller_get_interface()->get_features_ble()->as_array) ||
289             link_role == HCI_ROLE_MASTER) {
290           btsnd_hcic_ble_read_remote_feat(p->hci_handle);
291         } else {
292           btm_establish_continue(p);
293         }
294       } else {
295         btm_read_remote_features(p->hci_handle);
296       }
297
298       /* read page 1 - on rmt feature event for buffer reasons */
299       return;
300     }
301   }
302 }
303
304 void btm_acl_update_conn_addr(uint8_t conn_handle, BD_ADDR address) {
305   uint8_t idx = btm_handle_to_acl_index(conn_handle);
306   if (idx != MAX_L2CAP_LINKS) {
307     memcpy(btm_cb.acl_db[idx].conn_addr, address, BD_ADDR_LEN);
308   }
309 }
310
311 /*******************************************************************************
312  *
313  * Function         btm_acl_report_role_change
314  *
315  * Description      This function is called when the local device is deemed
316  *                  to be down. It notifies L2CAP of the failure.
317  *
318  * Returns          void
319  *
320  ******************************************************************************/
321 void btm_acl_report_role_change(uint8_t hci_status, BD_ADDR bda) {
322   tBTM_ROLE_SWITCH_CMPL ref_data;
323   BTM_TRACE_DEBUG("btm_acl_report_role_change");
324   if (btm_cb.devcb.p_switch_role_cb &&
325       (bda && (0 == memcmp(btm_cb.devcb.switch_role_ref_data.remote_bd_addr,
326                            bda, BD_ADDR_LEN)))) {
327     memcpy(&ref_data, &btm_cb.devcb.switch_role_ref_data,
328            sizeof(tBTM_ROLE_SWITCH_CMPL));
329     ref_data.hci_status = hci_status;
330     (*btm_cb.devcb.p_switch_role_cb)(&ref_data);
331     memset(&btm_cb.devcb.switch_role_ref_data, 0,
332            sizeof(tBTM_ROLE_SWITCH_CMPL));
333     btm_cb.devcb.p_switch_role_cb = NULL;
334   }
335 }
336
337 /*******************************************************************************
338  *
339  * Function         btm_acl_removed
340  *
341  * Description      This function is called by L2CAP when an ACL connection
342  *                  is removed. Since only L2CAP creates ACL links, we use
343  *                  the L2CAP link index as our index into the control blocks.
344  *
345  * Returns          void
346  *
347  ******************************************************************************/
348 void btm_acl_removed(BD_ADDR bda, tBT_TRANSPORT transport) {
349   tACL_CONN* p;
350   tBTM_BL_EVENT_DATA evt_data;
351   tBTM_SEC_DEV_REC* p_dev_rec = NULL;
352   BTM_TRACE_DEBUG("btm_acl_removed");
353   p = btm_bda_to_acl(bda, transport);
354   if (p != (tACL_CONN*)NULL) {
355     p->in_use = false;
356
357     /* if the disconnected channel has a pending role switch, clear it now */
358     btm_acl_report_role_change(HCI_ERR_NO_CONNECTION, bda);
359
360     /* Only notify if link up has had a chance to be issued */
361     if (p->link_up_issued) {
362       p->link_up_issued = false;
363
364       /* If anyone cares, tell him database changed */
365       if (btm_cb.p_bl_changed_cb) {
366         evt_data.event = BTM_BL_DISCN_EVT;
367         evt_data.discn.p_bda = bda;
368         evt_data.discn.handle = p->hci_handle;
369         evt_data.discn.transport = p->transport;
370         (*btm_cb.p_bl_changed_cb)(&evt_data);
371       }
372
373       btm_acl_update_busy_level(BTM_BLI_ACL_DOWN_EVT);
374     }
375
376     BTM_TRACE_DEBUG(
377         "acl hci_handle=%d transport=%d connectable_mode=0x%0x link_role=%d",
378         p->hci_handle, p->transport, btm_cb.ble_ctr_cb.inq_var.connectable_mode,
379         p->link_role);
380
381     p_dev_rec = btm_find_dev(bda);
382     if (p_dev_rec) {
383       BTM_TRACE_DEBUG("before update p_dev_rec->sec_flags=0x%x",
384                       p_dev_rec->sec_flags);
385       if (p->transport == BT_TRANSPORT_LE) {
386         BTM_TRACE_DEBUG("LE link down");
387         p_dev_rec->sec_flags &= ~(BTM_SEC_LE_ENCRYPTED | BTM_SEC_ROLE_SWITCHED);
388         if ((p_dev_rec->sec_flags & BTM_SEC_LE_LINK_KEY_KNOWN) == 0) {
389           BTM_TRACE_DEBUG("Not Bonded");
390           p_dev_rec->sec_flags &=
391               ~(BTM_SEC_LE_LINK_KEY_AUTHED | BTM_SEC_LE_AUTHENTICATED);
392         } else {
393           BTM_TRACE_DEBUG("Bonded");
394         }
395       } else {
396         BTM_TRACE_DEBUG("Bletooth link down");
397         p_dev_rec->sec_flags &= ~(BTM_SEC_AUTHORIZED | BTM_SEC_AUTHENTICATED |
398                                   BTM_SEC_ENCRYPTED | BTM_SEC_ROLE_SWITCHED);
399       }
400       BTM_TRACE_DEBUG("after update p_dev_rec->sec_flags=0x%x",
401                       p_dev_rec->sec_flags);
402     } else {
403       BTM_TRACE_ERROR("Device not found");
404     }
405
406     /* Clear the ACL connection data */
407     memset(p, 0, sizeof(tACL_CONN));
408   }
409 }
410
411 /*******************************************************************************
412  *
413  * Function         btm_acl_device_down
414  *
415  * Description      This function is called when the local device is deemed
416  *                  to be down. It notifies L2CAP of the failure.
417  *
418  * Returns          void
419  *
420  ******************************************************************************/
421 void btm_acl_device_down(void) {
422   tACL_CONN* p = &btm_cb.acl_db[0];
423   uint16_t xx;
424   BTM_TRACE_DEBUG("btm_acl_device_down");
425   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p++) {
426     if (p->in_use) {
427       BTM_TRACE_DEBUG("hci_handle=%d HCI_ERR_HW_FAILURE ", p->hci_handle);
428       l2c_link_hci_disc_comp(p->hci_handle, HCI_ERR_HW_FAILURE);
429     }
430   }
431 }
432
433 /*******************************************************************************
434  *
435  * Function         btm_acl_update_busy_level
436  *
437  * Description      This function is called to update the busy level of the
438  *                  system.
439  *
440  * Returns          void
441  *
442  ******************************************************************************/
443 void btm_acl_update_busy_level(tBTM_BLI_EVENT event) {
444   bool old_inquiry_state = btm_cb.is_inquiry;
445   tBTM_BL_UPDATE_DATA evt;
446   evt.busy_level_flags = 0;
447   switch (event) {
448     case BTM_BLI_ACL_UP_EVT:
449       BTM_TRACE_DEBUG("BTM_BLI_ACL_UP_EVT");
450       break;
451     case BTM_BLI_ACL_DOWN_EVT:
452       BTM_TRACE_DEBUG("BTM_BLI_ACL_DOWN_EVT");
453       break;
454     case BTM_BLI_PAGE_EVT:
455       BTM_TRACE_DEBUG("BTM_BLI_PAGE_EVT");
456       btm_cb.is_paging = true;
457       evt.busy_level_flags = BTM_BL_PAGING_STARTED;
458       break;
459     case BTM_BLI_PAGE_DONE_EVT:
460       BTM_TRACE_DEBUG("BTM_BLI_PAGE_DONE_EVT");
461       btm_cb.is_paging = false;
462       evt.busy_level_flags = BTM_BL_PAGING_COMPLETE;
463       break;
464     case BTM_BLI_INQ_EVT:
465       BTM_TRACE_DEBUG("BTM_BLI_INQ_EVT");
466       btm_cb.is_inquiry = true;
467       evt.busy_level_flags = BTM_BL_INQUIRY_STARTED;
468       break;
469     case BTM_BLI_INQ_CANCEL_EVT:
470       BTM_TRACE_DEBUG("BTM_BLI_INQ_CANCEL_EVT");
471       btm_cb.is_inquiry = false;
472       evt.busy_level_flags = BTM_BL_INQUIRY_CANCELLED;
473       break;
474     case BTM_BLI_INQ_DONE_EVT:
475       BTM_TRACE_DEBUG("BTM_BLI_INQ_DONE_EVT");
476       btm_cb.is_inquiry = false;
477       evt.busy_level_flags = BTM_BL_INQUIRY_COMPLETE;
478       break;
479   }
480
481   uint8_t busy_level;
482   if (btm_cb.is_paging || btm_cb.is_inquiry)
483     busy_level = 10;
484   else
485     busy_level = BTM_GetNumAclLinks();
486
487   if ((busy_level != btm_cb.busy_level) ||
488       (old_inquiry_state != btm_cb.is_inquiry)) {
489     evt.event = BTM_BL_UPDATE_EVT;
490     evt.busy_level = busy_level;
491     btm_cb.busy_level = busy_level;
492     if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_UPDATE_MASK)) {
493       (*btm_cb.p_bl_changed_cb)((tBTM_BL_EVENT_DATA*)&evt);
494     }
495   }
496 }
497
498 /*******************************************************************************
499  *
500  * Function         BTM_GetRole
501  *
502  * Description      This function is called to get the role of the local device
503  *                  for the ACL connection with the specified remote device
504  *
505  * Returns          BTM_SUCCESS if connection exists.
506  *                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
507  *
508  ******************************************************************************/
509 tBTM_STATUS BTM_GetRole(BD_ADDR remote_bd_addr, uint8_t* p_role) {
510   tACL_CONN* p;
511   BTM_TRACE_DEBUG("BTM_GetRole");
512   p = btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
513   if (p == NULL) {
514     *p_role = BTM_ROLE_UNDEFINED;
515     return (BTM_UNKNOWN_ADDR);
516   }
517
518   /* Get the current role */
519   *p_role = p->link_role;
520   return (BTM_SUCCESS);
521 }
522
523 /*******************************************************************************
524  *
525  * Function         BTM_SwitchRole
526  *
527  * Description      This function is called to switch role between master and
528  *                  slave.  If role is already set it will do nothing.  If the
529  *                  command was initiated, the callback function is called upon
530  *                  completion.
531  *
532  * Returns          BTM_SUCCESS if already in specified role.
533  *                  BTM_CMD_STARTED if command issued to controller.
534  *                  BTM_NO_RESOURCES if couldn't allocate memory to issue
535  *                                   command
536  *                  BTM_UNKNOWN_ADDR if no active link with bd addr specified
537  *                  BTM_MODE_UNSUPPORTED if local device does not support role
538  *                                       switching
539  *                  BTM_BUSY if the previous command is not completed
540  *
541  ******************************************************************************/
542 tBTM_STATUS BTM_SwitchRole(BD_ADDR remote_bd_addr, uint8_t new_role,
543                            tBTM_CMPL_CB* p_cb) {
544   tACL_CONN* p;
545   tBTM_SEC_DEV_REC* p_dev_rec = NULL;
546 #if (BTM_SCO_INCLUDED == TRUE)
547   bool is_sco_active;
548 #endif
549   tBTM_STATUS status;
550   tBTM_PM_MODE pwr_mode;
551   tBTM_PM_PWR_MD settings;
552   BD_ADDR_PTR p_bda;
553   BTM_TRACE_API("BTM_SwitchRole BDA: %02x-%02x-%02x-%02x-%02x-%02x",
554                 remote_bd_addr[0], remote_bd_addr[1], remote_bd_addr[2],
555                 remote_bd_addr[3], remote_bd_addr[4], remote_bd_addr[5]);
556
557   /* Make sure the local device supports switching */
558   if (!controller_get_interface()->supports_master_slave_role_switch())
559     return (BTM_MODE_UNSUPPORTED);
560
561   if (btm_cb.devcb.p_switch_role_cb && p_cb) {
562     p_bda = btm_cb.devcb.switch_role_ref_data.remote_bd_addr;
563     BTM_TRACE_DEBUG(
564         "Role switch on other device is in progress 0x%02x%02x%02x%02x%02x%02x",
565         p_bda[0], p_bda[1], p_bda[2], p_bda[3], p_bda[4], p_bda[5]);
566     return (BTM_BUSY);
567   }
568
569   p = btm_bda_to_acl(remote_bd_addr, BT_TRANSPORT_BR_EDR);
570   if (p == NULL) return (BTM_UNKNOWN_ADDR);
571
572   /* Finished if already in desired role */
573   if (p->link_role == new_role) return (BTM_SUCCESS);
574
575   if (interop_match_addr(INTEROP_DISABLE_ROLE_SWITCH,
576                          (const bt_bdaddr_t*)&remote_bd_addr)) {
577     return BTM_DEV_BLACKLISTED;
578   }
579
580 #if (BTM_SCO_INCLUDED == TRUE)
581   /* Check if there is any SCO Active on this BD Address */
582   is_sco_active = btm_is_sco_active_by_bdaddr(remote_bd_addr);
583
584   if (is_sco_active == true) return (BTM_NO_RESOURCES);
585 #endif
586
587   /* Ignore role switch request if the previous request was not completed */
588   if (p->switch_role_state != BTM_ACL_SWKEY_STATE_IDLE) {
589     BTM_TRACE_DEBUG("BTM_SwitchRole busy: %d", p->switch_role_state);
590     return (BTM_BUSY);
591   }
592
593   if (interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH,
594                          (const bt_bdaddr_t*)&remote_bd_addr)) {
595     BTM_TRACE_DEBUG("%s, Device blacklisted under INTEROP_DYNAMIC_ROLE_SWITCH.",
596                     __func__);
597     return BTM_DEV_BLACKLISTED;
598   }
599
600   status = BTM_ReadPowerMode(p->remote_addr, &pwr_mode);
601   if (status != BTM_SUCCESS) return (status);
602
603   /* Wake up the link if in sniff or park before attempting switch */
604   if (pwr_mode == BTM_PM_MD_PARK || pwr_mode == BTM_PM_MD_SNIFF) {
605     memset((void*)&settings, 0, sizeof(settings));
606     settings.mode = BTM_PM_MD_ACTIVE;
607     status = BTM_SetPowerMode(BTM_PM_SET_ONLY_ID, p->remote_addr, &settings);
608     if (status != BTM_CMD_STARTED) return (BTM_WRONG_MODE);
609
610     p->switch_role_state = BTM_ACL_SWKEY_STATE_MODE_CHANGE;
611   }
612   /* some devices do not support switch while encryption is on */
613   else {
614     p_dev_rec = btm_find_dev(remote_bd_addr);
615     if ((p_dev_rec != NULL) &&
616         ((p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) != 0) &&
617         !BTM_EPR_AVAILABLE(p)) {
618       /* bypass turning off encryption if change link key is already doing it */
619       if (p->encrypt_state != BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF) {
620         btsnd_hcic_set_conn_encrypt(p->hci_handle, false);
621         p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF;
622       }
623
624       p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF;
625     } else {
626       btsnd_hcic_switch_role(remote_bd_addr, new_role);
627       p->switch_role_state = BTM_ACL_SWKEY_STATE_IN_PROGRESS;
628
629 #if (BTM_DISC_DURING_RS == TRUE)
630       if (p_dev_rec) p_dev_rec->rs_disc_pending = BTM_SEC_RS_PENDING;
631 #endif
632     }
633   }
634
635   /* Initialize return structure in case request fails */
636   if (p_cb) {
637     memcpy(btm_cb.devcb.switch_role_ref_data.remote_bd_addr, remote_bd_addr,
638            BD_ADDR_LEN);
639     btm_cb.devcb.switch_role_ref_data.role = new_role;
640     /* initialized to an error code */
641     btm_cb.devcb.switch_role_ref_data.hci_status = HCI_ERR_UNSUPPORTED_VALUE;
642     btm_cb.devcb.p_switch_role_cb = p_cb;
643   }
644   return (BTM_CMD_STARTED);
645 }
646
647 /*******************************************************************************
648  *
649  * Function         btm_acl_encrypt_change
650  *
651  * Description      This function is when encryption of the connection is
652  *                  completed by the LM.  Checks to see if a role switch or
653  *                  change of link key was active and initiates or continues
654  *                  process if needed.
655  *
656  * Returns          void
657  *
658  ******************************************************************************/
659 void btm_acl_encrypt_change(uint16_t handle, uint8_t status,
660                             uint8_t encr_enable) {
661   tACL_CONN* p;
662   uint8_t xx;
663   tBTM_SEC_DEV_REC* p_dev_rec;
664   tBTM_BL_ROLE_CHG_DATA evt;
665
666   BTM_TRACE_DEBUG("btm_acl_encrypt_change handle=%d status=%d encr_enabl=%d",
667                   handle, status, encr_enable);
668   xx = btm_handle_to_acl_index(handle);
669   /* don't assume that we can never get a bad hci_handle */
670   if (xx < MAX_L2CAP_LINKS)
671     p = &btm_cb.acl_db[xx];
672   else
673     return;
674
675   /* Process Role Switch if active */
676   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF) {
677     /* if encryption turn off failed we still will try to switch role */
678     if (encr_enable) {
679       p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
680       p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
681     } else {
682       p->switch_role_state = BTM_ACL_SWKEY_STATE_SWITCHING;
683       p->encrypt_state = BTM_ACL_ENCRYPT_STATE_TEMP_FUNC;
684     }
685
686     btsnd_hcic_switch_role(p->remote_addr, (uint8_t)!p->link_role);
687 #if (BTM_DISC_DURING_RS == TRUE)
688     p_dev_rec = btm_find_dev(p->remote_addr);
689     if (p_dev_rec != NULL) p_dev_rec->rs_disc_pending = BTM_SEC_RS_PENDING;
690 #endif
691
692   }
693   /* Finished enabling Encryption after role switch */
694   else if (p->switch_role_state == BTM_ACL_SWKEY_STATE_ENCRYPTION_ON) {
695     p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
696     p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
697     btm_acl_report_role_change(btm_cb.devcb.switch_role_ref_data.hci_status,
698                                p->remote_addr);
699
700     /* if role change event is registered, report it now */
701     if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_ROLE_CHG_MASK)) {
702       evt.event = BTM_BL_ROLE_CHG_EVT;
703       evt.new_role = btm_cb.devcb.switch_role_ref_data.role;
704       evt.p_bda = btm_cb.devcb.switch_role_ref_data.remote_bd_addr;
705       evt.hci_status = btm_cb.devcb.switch_role_ref_data.hci_status;
706       (*btm_cb.p_bl_changed_cb)((tBTM_BL_EVENT_DATA*)&evt);
707
708       BTM_TRACE_DEBUG(
709           "Role Switch Event: new_role 0x%02x, HCI Status 0x%02x, rs_st:%d",
710           evt.new_role, evt.hci_status, p->switch_role_state);
711     }
712
713 #if (BTM_DISC_DURING_RS == TRUE)
714     /* If a disconnect is pending, issue it now that role switch has completed
715      */
716     p_dev_rec = btm_find_dev(p->remote_addr);
717     if (p_dev_rec != NULL) {
718       if (p_dev_rec->rs_disc_pending == BTM_SEC_DISC_PENDING) {
719         BTM_TRACE_WARNING(
720             "btm_acl_encrypt_change -> Issuing delayed HCI_Disconnect!!!");
721         btsnd_hcic_disconnect(p_dev_rec->hci_handle, HCI_ERR_PEER_USER);
722       }
723       BTM_TRACE_ERROR(
724           "btm_acl_encrypt_change: tBTM_SEC_DEV:0x%x rs_disc_pending=%d",
725           PTR_TO_UINT(p_dev_rec), p_dev_rec->rs_disc_pending);
726       p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
727     }
728 #endif
729   }
730 }
731 /*******************************************************************************
732  *
733  * Function         BTM_SetLinkPolicy
734  *
735  * Description      Create and send HCI "Write Policy Set" command
736  *
737  * Returns          status of the operation
738  *
739  ******************************************************************************/
740 tBTM_STATUS BTM_SetLinkPolicy(BD_ADDR remote_bda, uint16_t* settings) {
741   tACL_CONN* p;
742   uint8_t* localFeatures = BTM_ReadLocalFeatures();
743   BTM_TRACE_DEBUG("%s", __func__);
744   /*  BTM_TRACE_API ("%s: requested settings: 0x%04x", __func__, *settings ); */
745
746   /* First, check if hold mode is supported */
747   if (*settings != HCI_DISABLE_ALL_LM_MODES) {
748     if ((*settings & HCI_ENABLE_MASTER_SLAVE_SWITCH) &&
749         (!HCI_SWITCH_SUPPORTED(localFeatures))) {
750       *settings &= (~HCI_ENABLE_MASTER_SLAVE_SWITCH);
751       BTM_TRACE_API("BTM_SetLinkPolicy switch not supported (settings: 0x%04x)",
752                     *settings);
753     }
754     if ((*settings & HCI_ENABLE_HOLD_MODE) &&
755         (!HCI_HOLD_MODE_SUPPORTED(localFeatures))) {
756       *settings &= (~HCI_ENABLE_HOLD_MODE);
757       BTM_TRACE_API("BTM_SetLinkPolicy hold not supported (settings: 0x%04x)",
758                     *settings);
759     }
760     if ((*settings & HCI_ENABLE_SNIFF_MODE) &&
761         (!HCI_SNIFF_MODE_SUPPORTED(localFeatures))) {
762       *settings &= (~HCI_ENABLE_SNIFF_MODE);
763       BTM_TRACE_API("BTM_SetLinkPolicy sniff not supported (settings: 0x%04x)",
764                     *settings);
765     }
766     if ((*settings & HCI_ENABLE_PARK_MODE) &&
767         (!HCI_PARK_MODE_SUPPORTED(localFeatures))) {
768       *settings &= (~HCI_ENABLE_PARK_MODE);
769       BTM_TRACE_API("BTM_SetLinkPolicy park not supported (settings: 0x%04x)",
770                     *settings);
771     }
772   }
773
774   p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
775   if (p != NULL) {
776     btsnd_hcic_write_policy_set(p->hci_handle, *settings);
777     return BTM_CMD_STARTED;
778   }
779
780   /* If here, no BD Addr found */
781   return (BTM_UNKNOWN_ADDR);
782 }
783
784 /*******************************************************************************
785  *
786  * Function         BTM_SetDefaultLinkPolicy
787  *
788  * Description      Set the default value for HCI "Write Policy Set" command
789  *                  to use when an ACL link is created.
790  *
791  * Returns          void
792  *
793  ******************************************************************************/
794 void BTM_SetDefaultLinkPolicy(uint16_t settings) {
795   uint8_t* localFeatures = BTM_ReadLocalFeatures();
796
797   BTM_TRACE_DEBUG("BTM_SetDefaultLinkPolicy setting:0x%04x", settings);
798
799   if ((settings & HCI_ENABLE_MASTER_SLAVE_SWITCH) &&
800       (!HCI_SWITCH_SUPPORTED(localFeatures))) {
801     settings &= ~HCI_ENABLE_MASTER_SLAVE_SWITCH;
802     BTM_TRACE_DEBUG(
803         "BTM_SetDefaultLinkPolicy switch not supported (settings: 0x%04x)",
804         settings);
805   }
806   if ((settings & HCI_ENABLE_HOLD_MODE) &&
807       (!HCI_HOLD_MODE_SUPPORTED(localFeatures))) {
808     settings &= ~HCI_ENABLE_HOLD_MODE;
809     BTM_TRACE_DEBUG(
810         "BTM_SetDefaultLinkPolicy hold not supported (settings: 0x%04x)",
811         settings);
812   }
813   if ((settings & HCI_ENABLE_SNIFF_MODE) &&
814       (!HCI_SNIFF_MODE_SUPPORTED(localFeatures))) {
815     settings &= ~HCI_ENABLE_SNIFF_MODE;
816     BTM_TRACE_DEBUG(
817         "BTM_SetDefaultLinkPolicy sniff not supported (settings: 0x%04x)",
818         settings);
819   }
820   if ((settings & HCI_ENABLE_PARK_MODE) &&
821       (!HCI_PARK_MODE_SUPPORTED(localFeatures))) {
822     settings &= ~HCI_ENABLE_PARK_MODE;
823     BTM_TRACE_DEBUG(
824         "BTM_SetDefaultLinkPolicy park not supported (settings: 0x%04x)",
825         settings);
826   }
827   BTM_TRACE_DEBUG("Set DefaultLinkPolicy:0x%04x", settings);
828
829   btm_cb.btm_def_link_policy = settings;
830
831   /* Set the default Link Policy of the controller */
832   btsnd_hcic_write_def_policy_set(settings);
833 }
834
835 void btm_use_preferred_conn_params(BD_ADDR bda) {
836   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(bda, BT_TRANSPORT_LE);
837   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_or_alloc_dev(bda);
838
839   /* If there are any preferred connection parameters, set them now */
840   if ((p_dev_rec->conn_params.min_conn_int >= BTM_BLE_CONN_INT_MIN) &&
841       (p_dev_rec->conn_params.min_conn_int <= BTM_BLE_CONN_INT_MAX) &&
842       (p_dev_rec->conn_params.max_conn_int >= BTM_BLE_CONN_INT_MIN) &&
843       (p_dev_rec->conn_params.max_conn_int <= BTM_BLE_CONN_INT_MAX) &&
844       (p_dev_rec->conn_params.slave_latency <= BTM_BLE_CONN_LATENCY_MAX) &&
845       (p_dev_rec->conn_params.supervision_tout >= BTM_BLE_CONN_SUP_TOUT_MIN) &&
846       (p_dev_rec->conn_params.supervision_tout <= BTM_BLE_CONN_SUP_TOUT_MAX) &&
847       ((p_lcb->min_interval < p_dev_rec->conn_params.min_conn_int &&
848         p_dev_rec->conn_params.min_conn_int != BTM_BLE_CONN_PARAM_UNDEF) ||
849        (p_lcb->min_interval > p_dev_rec->conn_params.max_conn_int) ||
850        (p_lcb->latency > p_dev_rec->conn_params.slave_latency) ||
851        (p_lcb->timeout > p_dev_rec->conn_params.supervision_tout))) {
852     BTM_TRACE_DEBUG(
853         "%s: HANDLE=%d min_conn_int=%d max_conn_int=%d slave_latency=%d "
854         "supervision_tout=%d",
855         __func__, p_lcb->handle, p_dev_rec->conn_params.min_conn_int,
856         p_dev_rec->conn_params.max_conn_int,
857         p_dev_rec->conn_params.slave_latency,
858         p_dev_rec->conn_params.supervision_tout);
859
860     p_lcb->min_interval = p_dev_rec->conn_params.min_conn_int;
861     p_lcb->max_interval = p_dev_rec->conn_params.max_conn_int;
862     p_lcb->timeout = p_dev_rec->conn_params.supervision_tout;
863     p_lcb->latency = p_dev_rec->conn_params.slave_latency;
864
865     btsnd_hcic_ble_upd_ll_conn_params(
866         p_lcb->handle, p_dev_rec->conn_params.min_conn_int,
867         p_dev_rec->conn_params.max_conn_int,
868         p_dev_rec->conn_params.slave_latency,
869         p_dev_rec->conn_params.supervision_tout, 0, 0);
870   }
871 }
872
873 /*******************************************************************************
874  *
875  * Function         btm_read_remote_version_complete
876  *
877  * Description      This function is called when the command complete message
878  *                  is received from the HCI for the remote version info.
879  *
880  * Returns          void
881  *
882  ******************************************************************************/
883 void btm_read_remote_version_complete(uint8_t* p) {
884   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
885   uint8_t status;
886   uint16_t handle;
887   int xx;
888   BTM_TRACE_DEBUG("btm_read_remote_version_complete");
889
890   STREAM_TO_UINT8(status, p);
891   STREAM_TO_UINT16(handle, p);
892
893   /* Look up the connection by handle and copy features */
894   for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_acl_cb++) {
895     if ((p_acl_cb->in_use) && (p_acl_cb->hci_handle == handle)) {
896       if (status == HCI_SUCCESS) {
897         STREAM_TO_UINT8(p_acl_cb->lmp_version, p);
898         STREAM_TO_UINT16(p_acl_cb->manufacturer, p);
899         STREAM_TO_UINT16(p_acl_cb->lmp_subversion, p);
900       }
901
902       if (p_acl_cb->transport == BT_TRANSPORT_LE) {
903         l2cble_notify_le_connection(p_acl_cb->remote_addr);
904         btm_use_preferred_conn_params(p_acl_cb->remote_addr);
905       }
906       break;
907     }
908   }
909 }
910
911 /*******************************************************************************
912  *
913  * Function         btm_process_remote_ext_features
914  *
915  * Description      Local function called to process all extended features pages
916  *                  read from a remote device.
917  *
918  * Returns          void
919  *
920  ******************************************************************************/
921 void btm_process_remote_ext_features(tACL_CONN* p_acl_cb,
922                                      uint8_t num_read_pages) {
923   uint16_t handle = p_acl_cb->hci_handle;
924   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev_by_handle(handle);
925   uint8_t page_idx;
926
927   BTM_TRACE_DEBUG("btm_process_remote_ext_features");
928
929   /* Make sure we have the record to save remote features information */
930   if (p_dev_rec == NULL) {
931     /* Get a new device; might be doing dedicated bonding */
932     p_dev_rec = btm_find_or_alloc_dev(p_acl_cb->remote_addr);
933   }
934
935   p_acl_cb->num_read_pages = num_read_pages;
936   p_dev_rec->num_read_pages = num_read_pages;
937
938   /* Move the pages to placeholder */
939   for (page_idx = 0; page_idx < num_read_pages; page_idx++) {
940     if (page_idx > HCI_EXT_FEATURES_PAGE_MAX) {
941       BTM_TRACE_ERROR("%s: page=%d unexpected", __func__, page_idx);
942       break;
943     }
944     memcpy(p_dev_rec->feature_pages[page_idx],
945            p_acl_cb->peer_lmp_feature_pages[page_idx],
946            HCI_FEATURE_BYTES_PER_PAGE);
947   }
948
949   const uint8_t req_pend = (p_dev_rec->sm4 & BTM_SM4_REQ_PEND);
950
951   /* Store the Peer Security Capabilites (in SM4 and rmt_sec_caps) */
952   btm_sec_set_peer_sec_caps(p_acl_cb, p_dev_rec);
953
954   BTM_TRACE_API("%s: pend:%d", __func__, req_pend);
955   if (req_pend) {
956     /* Request for remaining Security Features (if any) */
957     l2cu_resubmit_pending_sec_req(p_dev_rec->bd_addr);
958   }
959 }
960
961 /*******************************************************************************
962  *
963  * Function         btm_read_remote_features
964  *
965  * Description      Local function called to send a read remote supported
966  *                  features/remote extended features page[0].
967  *
968  * Returns          void
969  *
970  ******************************************************************************/
971 void btm_read_remote_features(uint16_t handle) {
972   uint8_t acl_idx;
973   tACL_CONN* p_acl_cb;
974
975   BTM_TRACE_DEBUG("btm_read_remote_features() handle: %d", handle);
976
977   acl_idx = btm_handle_to_acl_index(handle);
978   if (acl_idx >= MAX_L2CAP_LINKS) {
979     BTM_TRACE_ERROR("btm_read_remote_features handle=%d invalid", handle);
980     return;
981   }
982
983   p_acl_cb = &btm_cb.acl_db[acl_idx];
984   p_acl_cb->num_read_pages = 0;
985   memset(p_acl_cb->peer_lmp_feature_pages, 0,
986          sizeof(p_acl_cb->peer_lmp_feature_pages));
987
988   /* first send read remote supported features HCI command */
989   /* because we don't know whether the remote support extended feature command
990    */
991   btsnd_hcic_rmt_features_req(handle);
992 }
993
994 /*******************************************************************************
995  *
996  * Function         btm_read_remote_ext_features
997  *
998  * Description      Local function called to send a read remote extended
999  *                  features
1000  *
1001  * Returns          void
1002  *
1003  ******************************************************************************/
1004 void btm_read_remote_ext_features(uint16_t handle, uint8_t page_number) {
1005   BTM_TRACE_DEBUG("btm_read_remote_ext_features() handle: %d page: %d", handle,
1006                   page_number);
1007
1008   btsnd_hcic_rmt_ext_features(handle, page_number);
1009 }
1010
1011 /*******************************************************************************
1012  *
1013  * Function         btm_read_remote_features_complete
1014  *
1015  * Description      This function is called when the remote supported features
1016  *                  complete event is received from the HCI.
1017  *
1018  * Returns          void
1019  *
1020  ******************************************************************************/
1021 void btm_read_remote_features_complete(uint8_t* p) {
1022   tACL_CONN* p_acl_cb;
1023   uint8_t status;
1024   uint16_t handle;
1025   uint8_t acl_idx;
1026
1027   BTM_TRACE_DEBUG("btm_read_remote_features_complete");
1028   STREAM_TO_UINT8(status, p);
1029
1030   if (status != HCI_SUCCESS) {
1031     BTM_TRACE_ERROR("btm_read_remote_features_complete failed (status 0x%02x)",
1032                     status);
1033     return;
1034   }
1035
1036   STREAM_TO_UINT16(handle, p);
1037
1038   acl_idx = btm_handle_to_acl_index(handle);
1039   if (acl_idx >= MAX_L2CAP_LINKS) {
1040     BTM_TRACE_ERROR("btm_read_remote_features_complete handle=%d invalid",
1041                     handle);
1042     return;
1043   }
1044
1045   p_acl_cb = &btm_cb.acl_db[acl_idx];
1046
1047   /* Copy the received features page */
1048   STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[0], p,
1049                   HCI_FEATURE_BYTES_PER_PAGE);
1050
1051   if ((HCI_LMP_EXTENDED_SUPPORTED(p_acl_cb->peer_lmp_feature_pages[0])) &&
1052       (controller_get_interface()
1053            ->supports_reading_remote_extended_features())) {
1054     /* if the remote controller has extended features and local controller
1055        supports HCI_Read_Remote_Extended_Features command then start reading
1056        these feature starting with extended features page 1 */
1057     BTM_TRACE_DEBUG("Start reading remote extended features");
1058     btm_read_remote_ext_features(handle, 1);
1059     return;
1060   }
1061
1062   /* Remote controller has no extended features. Process remote controller
1063      supported features (features page 0). */
1064   btm_process_remote_ext_features(p_acl_cb, 1);
1065
1066   /* Continue with HCI connection establishment */
1067   btm_establish_continue(p_acl_cb);
1068 }
1069
1070 /*******************************************************************************
1071  *
1072  * Function         btm_read_remote_ext_features_complete
1073  *
1074  * Description      This function is called when the remote extended features
1075  *                  complete event is received from the HCI.
1076  *
1077  * Returns          void
1078  *
1079  ******************************************************************************/
1080 void btm_read_remote_ext_features_complete(uint8_t* p, uint8_t evt_len) {
1081   tACL_CONN* p_acl_cb;
1082   uint8_t page_num, max_page;
1083   uint16_t handle;
1084   uint8_t acl_idx;
1085
1086   BTM_TRACE_DEBUG("btm_read_remote_ext_features_complete");
1087
1088   if (evt_len < HCI_EXT_FEATURES_SUCCESS_EVT_LEN) {
1089     android_errorWriteLog(0x534e4554, "141552859");
1090     BTM_TRACE_ERROR(
1091         "btm_read_remote_ext_features_complete evt length too short. length=%d",
1092         evt_len);
1093     return;
1094   }
1095
1096   ++p;
1097   STREAM_TO_UINT16(handle, p);
1098   STREAM_TO_UINT8(page_num, p);
1099   STREAM_TO_UINT8(max_page, p);
1100
1101   /* Validate parameters */
1102   acl_idx = btm_handle_to_acl_index(handle);
1103   if (acl_idx >= MAX_L2CAP_LINKS) {
1104     BTM_TRACE_ERROR("btm_read_remote_ext_features_complete handle=%d invalid",
1105                     handle);
1106     return;
1107   }
1108
1109   if (max_page > HCI_EXT_FEATURES_PAGE_MAX) {
1110     BTM_TRACE_ERROR("btm_read_remote_ext_features_complete page=%d unknown",
1111                     max_page);
1112     return;
1113   }
1114
1115   if (page_num > HCI_EXT_FEATURES_PAGE_MAX) {
1116     android_errorWriteLog(0x534e4554, "141552859");
1117     BTM_TRACE_ERROR("btm_read_remote_ext_features_complete num_page=%d invalid",
1118                     page_num);
1119     return;
1120   }
1121
1122   if (page_num > max_page) {
1123     BTM_TRACE_WARNING(
1124         "btm_read_remote_ext_features_complete num_page=%d, max_page=%d "
1125         "invalid", page_num, max_page);
1126   }
1127
1128   p_acl_cb = &btm_cb.acl_db[acl_idx];
1129
1130   /* Copy the received features page */
1131   STREAM_TO_ARRAY(p_acl_cb->peer_lmp_feature_pages[page_num], p,
1132                   HCI_FEATURE_BYTES_PER_PAGE);
1133
1134   /* If there is the next remote features page and
1135    * we have space to keep this page data - read this page */
1136   if ((page_num < max_page) && (page_num < HCI_EXT_FEATURES_PAGE_MAX)) {
1137     page_num++;
1138     BTM_TRACE_DEBUG("BTM reads next remote extended features page (%d)",
1139                     page_num);
1140     btm_read_remote_ext_features(handle, page_num);
1141     return;
1142   }
1143
1144   /* Reading of remote feature pages is complete */
1145   BTM_TRACE_DEBUG("BTM reached last remote extended features page (%d)",
1146                   page_num);
1147
1148   /* Process the pages */
1149   btm_process_remote_ext_features(p_acl_cb, (uint8_t)(page_num + 1));
1150
1151   /* Continue with HCI connection establishment */
1152   btm_establish_continue(p_acl_cb);
1153 }
1154
1155 /*******************************************************************************
1156  *
1157  * Function         btm_read_remote_ext_features_failed
1158  *
1159  * Description      This function is called when the remote extended features
1160  *                  complete event returns a failed status.
1161  *
1162  * Returns          void
1163  *
1164  ******************************************************************************/
1165 void btm_read_remote_ext_features_failed(uint8_t status, uint16_t handle) {
1166   tACL_CONN* p_acl_cb;
1167   uint8_t acl_idx;
1168
1169   BTM_TRACE_WARNING(
1170       "btm_read_remote_ext_features_failed (status 0x%02x) for handle %d",
1171       status, handle);
1172
1173   acl_idx = btm_handle_to_acl_index(handle);
1174   if (acl_idx >= MAX_L2CAP_LINKS) {
1175     BTM_TRACE_ERROR("btm_read_remote_ext_features_failed handle=%d invalid",
1176                     handle);
1177     return;
1178   }
1179
1180   p_acl_cb = &btm_cb.acl_db[acl_idx];
1181
1182   /* Process supported features only */
1183   btm_process_remote_ext_features(p_acl_cb, 1);
1184
1185   /* Continue HCI connection establishment */
1186   btm_establish_continue(p_acl_cb);
1187 }
1188
1189 /*******************************************************************************
1190  *
1191  * Function         btm_establish_continue
1192  *
1193  * Description      This function is called when the command complete message
1194  *                  is received from the HCI for the read local link policy
1195  *                  request.
1196  *
1197  * Returns          void
1198  *
1199  ******************************************************************************/
1200 void btm_establish_continue(tACL_CONN* p_acl_cb) {
1201   tBTM_BL_EVENT_DATA evt_data;
1202   BTM_TRACE_DEBUG("btm_establish_continue");
1203 #if (BTM_BYPASS_EXTRA_ACL_SETUP == FALSE)
1204   if (p_acl_cb->transport == BT_TRANSPORT_BR_EDR) {
1205     /* For now there are a some devices that do not like sending */
1206     /* commands events and data at the same time. */
1207     /* Set the packet types to the default allowed by the device */
1208     btm_set_packet_types(p_acl_cb, btm_cb.btm_acl_pkt_types_supported);
1209
1210     if (btm_cb.btm_def_link_policy)
1211       BTM_SetLinkPolicy(p_acl_cb->remote_addr, &btm_cb.btm_def_link_policy);
1212   }
1213 #endif
1214   p_acl_cb->link_up_issued = true;
1215
1216   /* If anyone cares, tell him database changed */
1217   if (btm_cb.p_bl_changed_cb) {
1218     evt_data.event = BTM_BL_CONN_EVT;
1219     evt_data.conn.p_bda = p_acl_cb->remote_addr;
1220     evt_data.conn.p_bdn = p_acl_cb->remote_name;
1221     evt_data.conn.p_dc = p_acl_cb->remote_dc;
1222     evt_data.conn.p_features = p_acl_cb->peer_lmp_feature_pages[0];
1223     evt_data.conn.handle = p_acl_cb->hci_handle;
1224     evt_data.conn.transport = p_acl_cb->transport;
1225
1226     (*btm_cb.p_bl_changed_cb)(&evt_data);
1227   }
1228   btm_acl_update_busy_level(BTM_BLI_ACL_UP_EVT);
1229 }
1230
1231 /*******************************************************************************
1232  *
1233  * Function         BTM_SetDefaultLinkSuperTout
1234  *
1235  * Description      Set the default value for HCI "Write Link Supervision
1236  *                                                 Timeout"
1237  *                  command to use when an ACL link is created.
1238  *
1239  * Returns          void
1240  *
1241  ******************************************************************************/
1242 void BTM_SetDefaultLinkSuperTout(uint16_t timeout) {
1243   BTM_TRACE_DEBUG("BTM_SetDefaultLinkSuperTout");
1244   btm_cb.btm_def_link_super_tout = timeout;
1245 }
1246
1247 /*******************************************************************************
1248  *
1249  * Function         BTM_GetLinkSuperTout
1250  *
1251  * Description      Read the link supervision timeout value of the connection
1252  *
1253  * Returns          status of the operation
1254  *
1255  ******************************************************************************/
1256 tBTM_STATUS BTM_GetLinkSuperTout(BD_ADDR remote_bda, uint16_t* p_timeout) {
1257   tACL_CONN* p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1258
1259   BTM_TRACE_DEBUG("BTM_GetLinkSuperTout");
1260   if (p != (tACL_CONN*)NULL) {
1261     *p_timeout = p->link_super_tout;
1262     return (BTM_SUCCESS);
1263   }
1264   /* If here, no BD Addr found */
1265   return (BTM_UNKNOWN_ADDR);
1266 }
1267
1268 /*******************************************************************************
1269  *
1270  * Function         BTM_SetLinkSuperTout
1271  *
1272  * Description      Create and send HCI "Write Link Supervision Timeout" command
1273  *
1274  * Returns          status of the operation
1275  *
1276  ******************************************************************************/
1277 tBTM_STATUS BTM_SetLinkSuperTout(BD_ADDR remote_bda, uint16_t timeout) {
1278   tACL_CONN* p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1279
1280   BTM_TRACE_DEBUG("BTM_SetLinkSuperTout");
1281   if (p != (tACL_CONN*)NULL) {
1282     p->link_super_tout = timeout;
1283
1284     /* Only send if current role is Master; 2.0 spec requires this */
1285     if (p->link_role == BTM_ROLE_MASTER) {
1286       btsnd_hcic_write_link_super_tout(LOCAL_BR_EDR_CONTROLLER_ID,
1287                                        p->hci_handle, timeout);
1288       return (BTM_CMD_STARTED);
1289     } else
1290       return (BTM_SUCCESS);
1291   }
1292
1293   /* If here, no BD Addr found */
1294   return (BTM_UNKNOWN_ADDR);
1295 }
1296
1297 /*******************************************************************************
1298  *
1299  * Function         BTM_IsAclConnectionUp
1300  *
1301  * Description      This function is called to check if an ACL connection exists
1302  *                  to a specific remote BD Address.
1303  *
1304  * Returns          true if connection is up, else false.
1305  *
1306  ******************************************************************************/
1307 bool BTM_IsAclConnectionUp(BD_ADDR remote_bda, tBT_TRANSPORT transport) {
1308   tACL_CONN* p;
1309
1310   BTM_TRACE_API("BTM_IsAclConnectionUp: RemBdAddr: %02x%02x%02x%02x%02x%02x",
1311                 remote_bda[0], remote_bda[1], remote_bda[2], remote_bda[3],
1312                 remote_bda[4], remote_bda[5]);
1313
1314   p = btm_bda_to_acl(remote_bda, transport);
1315   if (p != (tACL_CONN*)NULL) {
1316     return (true);
1317   }
1318
1319   /* If here, no BD Addr found */
1320   return (false);
1321 }
1322
1323 /*******************************************************************************
1324  *
1325  * Function         BTM_GetNumAclLinks
1326  *
1327  * Description      This function is called to count the number of
1328  *                  ACL links that are active.
1329  *
1330  * Returns          uint16_t Number of active ACL links
1331  *
1332  ******************************************************************************/
1333 uint16_t BTM_GetNumAclLinks(void) {
1334   uint16_t num_acl = 0;
1335
1336   for (uint16_t i = 0; i < MAX_L2CAP_LINKS; ++i) {
1337     if (btm_cb.acl_db[i].in_use) ++num_acl;
1338   }
1339
1340   return num_acl;
1341 }
1342
1343 /*******************************************************************************
1344  *
1345  * Function         btm_get_acl_disc_reason_code
1346  *
1347  * Description      This function is called to get the disconnection reason code
1348  *                  returned by the HCI at disconnection complete event.
1349  *
1350  * Returns          true if connection is up, else false.
1351  *
1352  ******************************************************************************/
1353 uint16_t btm_get_acl_disc_reason_code(void) {
1354   uint8_t res = btm_cb.acl_disc_reason;
1355   BTM_TRACE_DEBUG("btm_get_acl_disc_reason_code");
1356   return (res);
1357 }
1358
1359 /*******************************************************************************
1360  *
1361  * Function         BTM_GetHCIConnHandle
1362  *
1363  * Description      This function is called to get the handle for an ACL
1364  *                  connection to a specific remote BD Address.
1365  *
1366  * Returns          the handle of the connection, or 0xFFFF if none.
1367  *
1368  ******************************************************************************/
1369 uint16_t BTM_GetHCIConnHandle(const BD_ADDR remote_bda,
1370                               tBT_TRANSPORT transport) {
1371   tACL_CONN* p;
1372   BTM_TRACE_DEBUG("BTM_GetHCIConnHandle");
1373   p = btm_bda_to_acl(remote_bda, transport);
1374   if (p != (tACL_CONN*)NULL) {
1375     return (p->hci_handle);
1376   }
1377
1378   /* If here, no BD Addr found */
1379   return (0xFFFF);
1380 }
1381
1382 /*******************************************************************************
1383  *
1384  * Function         btm_process_clk_off_comp_evt
1385  *
1386  * Description      This function is called when clock offset command completes.
1387  *
1388  * Input Parms      hci_handle - connection handle associated with the change
1389  *                  clock offset
1390  *
1391  * Returns          void
1392  *
1393  ******************************************************************************/
1394 void btm_process_clk_off_comp_evt(uint16_t hci_handle, uint16_t clock_offset) {
1395   uint8_t xx;
1396   BTM_TRACE_DEBUG("btm_process_clk_off_comp_evt");
1397   /* Look up the connection by handle and set the current mode */
1398   xx = btm_handle_to_acl_index(hci_handle);
1399   if (xx < MAX_L2CAP_LINKS) btm_cb.acl_db[xx].clock_offset = clock_offset;
1400 }
1401
1402 /*******************************************************************************
1403 *
1404 * Function         btm_blacklist_role_change_device
1405 *
1406 * Description      This function is used to blacklist the device if the role
1407 *                  switch fails for maximum number of times. It also removes
1408 *                  the device from the black list if the role switch succeeds.
1409 *
1410 * Input Parms      bd_addr - remote BD addr
1411 *                  hci_status - role switch status
1412 *
1413 * Returns          void
1414 *
1415 *******************************************************************************/
1416 void btm_blacklist_role_change_device(BD_ADDR bd_addr, uint8_t hci_status) {
1417   tACL_CONN* p = btm_bda_to_acl(bd_addr, BT_TRANSPORT_BR_EDR);
1418   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
1419
1420   if (!p || !p_dev_rec) {
1421     return;
1422   }
1423   if (hci_status == HCI_SUCCESS) {
1424     p->switch_role_failed_attempts = 0;
1425     return;
1426   }
1427
1428   /* check for carkits */
1429   const uint32_t cod_audio_device =
1430       (BTM_COD_SERVICE_AUDIO | BTM_COD_MAJOR_AUDIO) << 8;
1431   const uint32_t cod =
1432       ((p_dev_rec->dev_class[0] << 16) | (p_dev_rec->dev_class[1] << 8) |
1433        p_dev_rec->dev_class[2]) &
1434       0xffffff;
1435   if ((hci_status != HCI_SUCCESS) &&
1436       ((p->switch_role_state == BTM_ACL_SWKEY_STATE_SWITCHING) ||
1437        (p->switch_role_state == BTM_ACL_SWKEY_STATE_IN_PROGRESS)) &&
1438       ((cod & cod_audio_device) == cod_audio_device) &&
1439       (!interop_match_addr(INTEROP_DYNAMIC_ROLE_SWITCH,
1440                            (const bt_bdaddr_t*)&bd_addr))) {
1441     p->switch_role_failed_attempts++;
1442     if (p->switch_role_failed_attempts == BTM_MAX_SW_ROLE_FAILED_ATTEMPTS) {
1443       BTM_TRACE_WARNING(
1444           "%s: Device %02x:%02x:%02x:%02x:%02x:%02x blacklisted for role "
1445           "switching - multiple role switch failed attempts: %u",
1446           __func__, bd_addr[0], bd_addr[1], bd_addr[2], bd_addr[3], bd_addr[4],
1447           bd_addr[5], p->switch_role_failed_attempts);
1448       interop_database_add(INTEROP_DYNAMIC_ROLE_SWITCH,
1449                            (const bt_bdaddr_t*)&bd_addr, 3);
1450     }
1451   }
1452 }
1453
1454 /*******************************************************************************
1455  *
1456  * Function         btm_acl_role_changed
1457  *
1458  * Description      This function is called whan a link's master/slave role
1459  *                  change event or command status event (with error) is
1460  *                  received. It updates the link control block, and calls the
1461  *                  registered callback with status and role (if registered).
1462  *
1463  * Returns          void
1464  *
1465  ******************************************************************************/
1466 void btm_acl_role_changed(uint8_t hci_status, BD_ADDR bd_addr,
1467                           uint8_t new_role) {
1468   uint8_t* p_bda =
1469       (bd_addr) ? bd_addr : btm_cb.devcb.switch_role_ref_data.remote_bd_addr;
1470   tACL_CONN* p = btm_bda_to_acl(p_bda, BT_TRANSPORT_BR_EDR);
1471   tBTM_ROLE_SWITCH_CMPL* p_data = &btm_cb.devcb.switch_role_ref_data;
1472   tBTM_SEC_DEV_REC* p_dev_rec;
1473   tBTM_BL_ROLE_CHG_DATA evt;
1474
1475   BTM_TRACE_DEBUG("btm_acl_role_changed");
1476   /* Ignore any stray events */
1477   if (p == NULL) {
1478     /* it could be a failure */
1479     if (hci_status != HCI_SUCCESS)
1480       btm_acl_report_role_change(hci_status, bd_addr);
1481     return;
1482   }
1483
1484   p_data->hci_status = hci_status;
1485
1486   if (hci_status == HCI_SUCCESS) {
1487     p_data->role = new_role;
1488     memcpy(p_data->remote_bd_addr, p_bda, BD_ADDR_LEN);
1489
1490     /* Update cached value */
1491     p->link_role = new_role;
1492
1493     /* Reload LSTO: link supervision timeout is reset in the LM after a role
1494      * switch */
1495     if (new_role == BTM_ROLE_MASTER) {
1496       BTM_SetLinkSuperTout(p->remote_addr, p->link_super_tout);
1497     }
1498   } else {
1499     /* so the BTM_BL_ROLE_CHG_EVT uses the old role */
1500     new_role = p->link_role;
1501   }
1502
1503   /* Check if any SCO req is pending for role change */
1504   btm_sco_chk_pend_rolechange(p->hci_handle);
1505
1506   /* if switching state is switching we need to turn encryption on */
1507   /* if idle, we did not change encryption */
1508   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_SWITCHING) {
1509     btsnd_hcic_set_conn_encrypt(p->hci_handle, true);
1510     p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_ON;
1511     p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_ON;
1512     return;
1513   }
1514
1515   /* Set the switch_role_state to IDLE since the reply received from HCI */
1516   /* regardless of its result either success or failed. */
1517   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_IN_PROGRESS) {
1518     p->switch_role_state = BTM_ACL_SWKEY_STATE_IDLE;
1519     p->encrypt_state = BTM_ACL_ENCRYPT_STATE_IDLE;
1520   }
1521
1522   /* if role switch complete is needed, report it now */
1523   btm_acl_report_role_change(hci_status, bd_addr);
1524
1525   /* if role change event is registered, report it now */
1526   if (btm_cb.p_bl_changed_cb && (btm_cb.bl_evt_mask & BTM_BL_ROLE_CHG_MASK)) {
1527     evt.event = BTM_BL_ROLE_CHG_EVT;
1528     evt.new_role = new_role;
1529     evt.p_bda = p_bda;
1530     evt.hci_status = hci_status;
1531     (*btm_cb.p_bl_changed_cb)((tBTM_BL_EVENT_DATA*)&evt);
1532   }
1533
1534   BTM_TRACE_DEBUG(
1535       "Role Switch Event: new_role 0x%02x, HCI Status 0x%02x, rs_st:%d",
1536       p_data->role, p_data->hci_status, p->switch_role_state);
1537
1538 #if (BTM_DISC_DURING_RS == TRUE)
1539   /* If a disconnect is pending, issue it now that role switch has completed */
1540   p_dev_rec = btm_find_dev(p_bda);
1541   if (p_dev_rec != NULL) {
1542     if (p_dev_rec->rs_disc_pending == BTM_SEC_DISC_PENDING) {
1543       BTM_TRACE_WARNING(
1544           "btm_acl_role_changed -> Issuing delayed HCI_Disconnect!!!");
1545       btsnd_hcic_disconnect(p_dev_rec->hci_handle, HCI_ERR_PEER_USER);
1546     }
1547     BTM_TRACE_ERROR("tBTM_SEC_DEV:0x%x rs_disc_pending=%d",
1548                     PTR_TO_UINT(p_dev_rec), p_dev_rec->rs_disc_pending);
1549     p_dev_rec->rs_disc_pending = BTM_SEC_RS_NOT_PENDING; /* reset flag */
1550   }
1551
1552 #endif
1553 }
1554
1555 /*******************************************************************************
1556  *
1557  * Function         BTM_AllocateSCN
1558  *
1559  * Description      Look through the Server Channel Numbers for a free one.
1560  *
1561  * Returns          Allocated SCN number or 0 if none.
1562  *
1563  ******************************************************************************/
1564
1565 uint8_t BTM_AllocateSCN(void) {
1566   uint8_t x;
1567   BTM_TRACE_DEBUG("BTM_AllocateSCN");
1568
1569   // stack reserves scn 1 for HFP, HSP we still do the correct way
1570   for (x = 1; x < BTM_MAX_SCN; x++) {
1571     if (!btm_cb.btm_scn[x]) {
1572       btm_cb.btm_scn[x] = true;
1573       return (x + 1);
1574     }
1575   }
1576
1577   return (0); /* No free ports */
1578 }
1579
1580 /*******************************************************************************
1581  *
1582  * Function         BTM_TryAllocateSCN
1583  *
1584  * Description      Try to allocate a fixed server channel
1585  *
1586  * Returns          Returns true if server channel was available
1587  *
1588  ******************************************************************************/
1589
1590 bool BTM_TryAllocateSCN(uint8_t scn) {
1591   /* Make sure we don't exceed max port range.
1592    * Stack reserves scn 1 for HFP, HSP we still do the correct way.
1593    */
1594   if ((scn >= BTM_MAX_SCN) || (scn == 1)) return false;
1595
1596   /* check if this port is available */
1597   if (!btm_cb.btm_scn[scn - 1]) {
1598     btm_cb.btm_scn[scn - 1] = true;
1599     return true;
1600   }
1601
1602   return (false); /* Port was busy */
1603 }
1604
1605 /*******************************************************************************
1606  *
1607  * Function         BTM_FreeSCN
1608  *
1609  * Description      Free the specified SCN.
1610  *
1611  * Returns          true or false
1612  *
1613  ******************************************************************************/
1614 bool BTM_FreeSCN(uint8_t scn) {
1615   BTM_TRACE_DEBUG("BTM_FreeSCN ");
1616   if (scn <= BTM_MAX_SCN) {
1617     btm_cb.btm_scn[scn - 1] = false;
1618     return (true);
1619   } else
1620     return (false); /* Illegal SCN passed in */
1621 }
1622
1623 /*******************************************************************************
1624  *
1625  * Function         btm_set_packet_types
1626  *
1627  * Description      This function sets the packet types used for a specific
1628  *                  ACL connection. It is called internally by btm_acl_created
1629  *                  or by an application/profile by BTM_SetPacketTypes.
1630  *
1631  * Returns          status of the operation
1632  *
1633  ******************************************************************************/
1634 tBTM_STATUS btm_set_packet_types(tACL_CONN* p, uint16_t pkt_types) {
1635   uint16_t temp_pkt_types;
1636   BTM_TRACE_DEBUG("btm_set_packet_types");
1637   /* Save in the ACL control blocks, types that we support */
1638   temp_pkt_types = (pkt_types & BTM_ACL_SUPPORTED_PKTS_MASK &
1639                     btm_cb.btm_acl_pkt_types_supported);
1640
1641   /* OR in any exception packet types if at least 2.0 version of spec */
1642   temp_pkt_types |=
1643       ((pkt_types & BTM_ACL_EXCEPTION_PKTS_MASK) |
1644        (btm_cb.btm_acl_pkt_types_supported & BTM_ACL_EXCEPTION_PKTS_MASK));
1645
1646   /* Exclude packet types not supported by the peer */
1647   btm_acl_chk_peer_pkt_type_support(p, &temp_pkt_types);
1648
1649   BTM_TRACE_DEBUG("SetPacketType Mask -> 0x%04x", temp_pkt_types);
1650
1651   btsnd_hcic_change_conn_type(p->hci_handle, temp_pkt_types);
1652   p->pkt_types_mask = temp_pkt_types;
1653
1654   return (BTM_CMD_STARTED);
1655 }
1656
1657 /*******************************************************************************
1658  *
1659  * Function         btm_get_max_packet_size
1660  *
1661  * Returns          Returns maximum packet size that can be used for current
1662  *                  connection, 0 if connection is not established
1663  *
1664  ******************************************************************************/
1665 uint16_t btm_get_max_packet_size(BD_ADDR addr) {
1666   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1667   uint16_t pkt_types = 0;
1668   uint16_t pkt_size = 0;
1669   BTM_TRACE_DEBUG("btm_get_max_packet_size");
1670   if (p != NULL) {
1671     pkt_types = p->pkt_types_mask;
1672   } else {
1673     /* Special case for when info for the local device is requested */
1674     if (memcmp(controller_get_interface()->get_address(), addr, BD_ADDR_LEN) ==
1675         0) {
1676       pkt_types = btm_cb.btm_acl_pkt_types_supported;
1677     }
1678   }
1679
1680   if (pkt_types) {
1681     if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_3_DH5))
1682       pkt_size = HCI_EDR3_DH5_PACKET_SIZE;
1683     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_2_DH5))
1684       pkt_size = HCI_EDR2_DH5_PACKET_SIZE;
1685     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_3_DH3))
1686       pkt_size = HCI_EDR3_DH3_PACKET_SIZE;
1687     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DH5)
1688       pkt_size = HCI_DH5_PACKET_SIZE;
1689     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_2_DH3))
1690       pkt_size = HCI_EDR2_DH3_PACKET_SIZE;
1691     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DM5)
1692       pkt_size = HCI_DM5_PACKET_SIZE;
1693     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DH3)
1694       pkt_size = HCI_DH3_PACKET_SIZE;
1695     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DM3)
1696       pkt_size = HCI_DM3_PACKET_SIZE;
1697     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_3_DH1))
1698       pkt_size = HCI_EDR3_DH1_PACKET_SIZE;
1699     else if (!(pkt_types & BTM_ACL_PKT_TYPES_MASK_NO_2_DH1))
1700       pkt_size = HCI_EDR2_DH1_PACKET_SIZE;
1701     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DH1)
1702       pkt_size = HCI_DH1_PACKET_SIZE;
1703     else if (pkt_types & BTM_ACL_PKT_TYPES_MASK_DM1)
1704       pkt_size = HCI_DM1_PACKET_SIZE;
1705   }
1706
1707   return (pkt_size);
1708 }
1709
1710 /*******************************************************************************
1711  *
1712  * Function         BTM_ReadRemoteVersion
1713  *
1714  * Returns          If connected report peer device info
1715  *
1716  ******************************************************************************/
1717 tBTM_STATUS BTM_ReadRemoteVersion(BD_ADDR addr, uint8_t* lmp_version,
1718                                   uint16_t* manufacturer,
1719                                   uint16_t* lmp_sub_version) {
1720   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1721   BTM_TRACE_DEBUG("BTM_ReadRemoteVersion");
1722   if (p == NULL) return (BTM_UNKNOWN_ADDR);
1723
1724   if (lmp_version) *lmp_version = p->lmp_version;
1725
1726   if (manufacturer) *manufacturer = p->manufacturer;
1727
1728   if (lmp_sub_version) *lmp_sub_version = p->lmp_subversion;
1729
1730   return (BTM_SUCCESS);
1731 }
1732
1733 /*******************************************************************************
1734  *
1735  * Function         BTM_ReadRemoteFeatures
1736  *
1737  * Returns          pointer to the remote supported features mask (8 bytes)
1738  *
1739  ******************************************************************************/
1740 uint8_t* BTM_ReadRemoteFeatures(BD_ADDR addr) {
1741   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1742   BTM_TRACE_DEBUG("BTM_ReadRemoteFeatures");
1743   if (p == NULL) {
1744     return (NULL);
1745   }
1746
1747   return (p->peer_lmp_feature_pages[0]);
1748 }
1749
1750 /*******************************************************************************
1751  *
1752  * Function         BTM_ReadRemoteExtendedFeatures
1753  *
1754  * Returns          pointer to the remote extended features mask (8 bytes)
1755  *                  or NULL if bad page
1756  *
1757  ******************************************************************************/
1758 uint8_t* BTM_ReadRemoteExtendedFeatures(BD_ADDR addr, uint8_t page_number) {
1759   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1760   BTM_TRACE_DEBUG("BTM_ReadRemoteExtendedFeatures");
1761   if (p == NULL) {
1762     return (NULL);
1763   }
1764
1765   if (page_number > HCI_EXT_FEATURES_PAGE_MAX) {
1766     BTM_TRACE_ERROR("Warning: BTM_ReadRemoteExtendedFeatures page %d unknown",
1767                     page_number);
1768     return NULL;
1769   }
1770
1771   return (p->peer_lmp_feature_pages[page_number]);
1772 }
1773
1774 /*******************************************************************************
1775  *
1776  * Function         BTM_ReadNumberRemoteFeaturesPages
1777  *
1778  * Returns          number of features pages read from the remote device.
1779  *
1780  ******************************************************************************/
1781 uint8_t BTM_ReadNumberRemoteFeaturesPages(BD_ADDR addr) {
1782   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1783   BTM_TRACE_DEBUG("BTM_ReadNumberRemoteFeaturesPages");
1784   if (p == NULL) {
1785     return (0);
1786   }
1787
1788   return (p->num_read_pages);
1789 }
1790
1791 /*******************************************************************************
1792  *
1793  * Function         BTM_ReadAllRemoteFeatures
1794  *
1795  * Returns          pointer to all features of the remote (24 bytes).
1796  *
1797  ******************************************************************************/
1798 uint8_t* BTM_ReadAllRemoteFeatures(BD_ADDR addr) {
1799   tACL_CONN* p = btm_bda_to_acl(addr, BT_TRANSPORT_BR_EDR);
1800   BTM_TRACE_DEBUG("BTM_ReadAllRemoteFeatures");
1801   if (p == NULL) {
1802     return (NULL);
1803   }
1804
1805   return (p->peer_lmp_feature_pages[0]);
1806 }
1807
1808 /*******************************************************************************
1809  *
1810  * Function         BTM_RegBusyLevelNotif
1811  *
1812  * Description      This function is called to register a callback to receive
1813  *                  busy level change events.
1814  *
1815  * Returns          BTM_SUCCESS if successfully registered, otherwise error
1816  *
1817  ******************************************************************************/
1818 tBTM_STATUS BTM_RegBusyLevelNotif(tBTM_BL_CHANGE_CB* p_cb, uint8_t* p_level,
1819                                   tBTM_BL_EVENT_MASK evt_mask) {
1820   BTM_TRACE_DEBUG("BTM_RegBusyLevelNotif");
1821   if (p_level) *p_level = btm_cb.busy_level;
1822
1823   btm_cb.bl_evt_mask = evt_mask;
1824
1825   if (!p_cb)
1826     btm_cb.p_bl_changed_cb = NULL;
1827   else if (btm_cb.p_bl_changed_cb)
1828     return (BTM_BUSY);
1829   else
1830     btm_cb.p_bl_changed_cb = p_cb;
1831
1832   return (BTM_SUCCESS);
1833 }
1834
1835 /*******************************************************************************
1836  *
1837  * Function         BTM_SetQoS
1838  *
1839  * Description      This function is called to setup QoS
1840  *
1841  * Returns          status of the operation
1842  *
1843  ******************************************************************************/
1844 tBTM_STATUS BTM_SetQoS(BD_ADDR bd, FLOW_SPEC* p_flow, tBTM_CMPL_CB* p_cb) {
1845   tACL_CONN* p = &btm_cb.acl_db[0];
1846
1847   BTM_TRACE_API("BTM_SetQoS: BdAddr: %02x%02x%02x%02x%02x%02x", bd[0], bd[1],
1848                 bd[2], bd[3], bd[4], bd[5]);
1849
1850   /* If someone already waiting on the version, do not allow another */
1851   if (btm_cb.devcb.p_qos_setup_cmpl_cb) return (BTM_BUSY);
1852
1853   p = btm_bda_to_acl(bd, BT_TRANSPORT_BR_EDR);
1854   if (p != NULL) {
1855     btm_cb.devcb.p_qos_setup_cmpl_cb = p_cb;
1856     alarm_set_on_queue(btm_cb.devcb.qos_setup_timer, BTM_DEV_REPLY_TIMEOUT_MS,
1857                        btm_qos_setup_timeout, NULL, btu_general_alarm_queue);
1858
1859     btsnd_hcic_qos_setup(p->hci_handle, p_flow->qos_flags, p_flow->service_type,
1860                          p_flow->token_rate, p_flow->peak_bandwidth,
1861                          p_flow->latency, p_flow->delay_variation);
1862     return (BTM_CMD_STARTED);
1863   }
1864
1865   /* If here, no BD Addr found */
1866   return (BTM_UNKNOWN_ADDR);
1867 }
1868
1869 /*******************************************************************************
1870  *
1871  * Function         btm_qos_setup_timeout
1872  *
1873  * Description      Callback when QoS setup times out.
1874  *
1875  * Returns          void
1876  *
1877  ******************************************************************************/
1878 void btm_qos_setup_timeout(UNUSED_ATTR void* data) {
1879   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_qos_setup_cmpl_cb;
1880   btm_cb.devcb.p_qos_setup_cmpl_cb = NULL;
1881   if (p_cb) (*p_cb)((void*)NULL);
1882 }
1883
1884 /*******************************************************************************
1885  *
1886  * Function         btm_qos_setup_complete
1887  *
1888  * Description      This function is called when the command complete message
1889  *                  is received from the HCI for the qos setup request.
1890  *
1891  * Returns          void
1892  *
1893  ******************************************************************************/
1894 void btm_qos_setup_complete(uint8_t status, uint16_t handle,
1895                             FLOW_SPEC* p_flow) {
1896   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_qos_setup_cmpl_cb;
1897   tBTM_QOS_SETUP_CMPL qossu;
1898
1899   BTM_TRACE_DEBUG("%s", __func__);
1900   alarm_cancel(btm_cb.devcb.qos_setup_timer);
1901   btm_cb.devcb.p_qos_setup_cmpl_cb = NULL;
1902
1903   /* If there was a registered callback, call it */
1904   if (p_cb) {
1905     memset(&qossu, 0, sizeof(tBTM_QOS_SETUP_CMPL));
1906     qossu.status = status;
1907     qossu.handle = handle;
1908     if (p_flow != NULL) {
1909       qossu.flow.qos_flags = p_flow->qos_flags;
1910       qossu.flow.service_type = p_flow->service_type;
1911       qossu.flow.token_rate = p_flow->token_rate;
1912       qossu.flow.peak_bandwidth = p_flow->peak_bandwidth;
1913       qossu.flow.latency = p_flow->latency;
1914       qossu.flow.delay_variation = p_flow->delay_variation;
1915     }
1916     BTM_TRACE_DEBUG("BTM: p_flow->delay_variation: 0x%02x",
1917                     qossu.flow.delay_variation);
1918     (*p_cb)(&qossu);
1919   }
1920 }
1921
1922 /*******************************************************************************
1923  *
1924  * Function         BTM_ReadRSSI
1925  *
1926  * Description      This function is called to read the link policy settings.
1927  *                  The address of link policy results are returned in the
1928  *                  callback.
1929  *                  (tBTM_RSSI_RESULTS)
1930  *
1931  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1932  *
1933  ******************************************************************************/
1934 tBTM_STATUS BTM_ReadRSSI(const BD_ADDR remote_bda, tBTM_CMPL_CB* p_cb) {
1935   tACL_CONN* p;
1936   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1937   tBT_DEVICE_TYPE dev_type;
1938   tBLE_ADDR_TYPE addr_type;
1939   BTM_TRACE_API("BTM_ReadRSSI: RemBdAddr: %02x%02x%02x%02x%02x%02x",
1940                 remote_bda[0], remote_bda[1], remote_bda[2], remote_bda[3],
1941                 remote_bda[4], remote_bda[5]);
1942
1943   /* If someone already waiting on the version, do not allow another */
1944   if (btm_cb.devcb.p_rssi_cmpl_cb) return (BTM_BUSY);
1945
1946   BTM_ReadDevInfo(remote_bda, &dev_type, &addr_type);
1947   if (dev_type == BT_DEVICE_TYPE_BLE) transport = BT_TRANSPORT_LE;
1948
1949   p = btm_bda_to_acl(remote_bda, transport);
1950   if (p != (tACL_CONN*)NULL) {
1951     btm_cb.devcb.p_rssi_cmpl_cb = p_cb;
1952     alarm_set_on_queue(btm_cb.devcb.read_rssi_timer, BTM_DEV_REPLY_TIMEOUT_MS,
1953                        btm_read_rssi_timeout, NULL, btu_general_alarm_queue);
1954
1955     btsnd_hcic_read_rssi(p->hci_handle);
1956     return (BTM_CMD_STARTED);
1957   }
1958
1959   /* If here, no BD Addr found */
1960   return (BTM_UNKNOWN_ADDR);
1961 }
1962
1963 /*******************************************************************************
1964  *
1965  * Function         BTM_ReadLinkQuality
1966  *
1967  * Description      This function is called to read the link qulaity.
1968  *                  The value of the link quality is returned in the callback.
1969  *                  (tBTM_LINK_QUALITY_RESULTS)
1970  *
1971  * Returns          BTM_CMD_STARTED if successfully initiated or error code
1972  *
1973  ******************************************************************************/
1974 tBTM_STATUS BTM_ReadLinkQuality(BD_ADDR remote_bda, tBTM_CMPL_CB* p_cb) {
1975   tACL_CONN* p;
1976
1977   BTM_TRACE_API("BTM_ReadLinkQuality: RemBdAddr: %02x%02x%02x%02x%02x%02x",
1978                 remote_bda[0], remote_bda[1], remote_bda[2], remote_bda[3],
1979                 remote_bda[4], remote_bda[5]);
1980
1981   /* If someone already waiting on the version, do not allow another */
1982   if (btm_cb.devcb.p_link_qual_cmpl_cb) return (BTM_BUSY);
1983
1984   p = btm_bda_to_acl(remote_bda, BT_TRANSPORT_BR_EDR);
1985   if (p != (tACL_CONN*)NULL) {
1986     btm_cb.devcb.p_link_qual_cmpl_cb = p_cb;
1987     alarm_set_on_queue(btm_cb.devcb.read_link_quality_timer,
1988                        BTM_DEV_REPLY_TIMEOUT_MS, btm_read_link_quality_timeout,
1989                        NULL, btu_general_alarm_queue);
1990
1991     btsnd_hcic_get_link_quality(p->hci_handle);
1992     return (BTM_CMD_STARTED);
1993   }
1994
1995   /* If here, no BD Addr found */
1996   return (BTM_UNKNOWN_ADDR);
1997 }
1998
1999 /*******************************************************************************
2000  *
2001  * Function         BTM_ReadTxPower
2002  *
2003  * Description      This function is called to read the current
2004  *                  TX power of the connection. The tx power level results
2005  *                  are returned in the callback.
2006  *                  (tBTM_RSSI_RESULTS)
2007  *
2008  * Returns          BTM_CMD_STARTED if successfully initiated or error code
2009  *
2010  ******************************************************************************/
2011 tBTM_STATUS BTM_ReadTxPower(BD_ADDR remote_bda, tBT_TRANSPORT transport,
2012                             tBTM_CMPL_CB* p_cb) {
2013   tACL_CONN* p;
2014 #define BTM_READ_RSSI_TYPE_CUR 0x00
2015 #define BTM_READ_RSSI_TYPE_MAX 0X01
2016
2017   BTM_TRACE_API("BTM_ReadTxPower: RemBdAddr: %02x%02x%02x%02x%02x%02x",
2018                 remote_bda[0], remote_bda[1], remote_bda[2], remote_bda[3],
2019                 remote_bda[4], remote_bda[5]);
2020
2021   /* If someone already waiting on the version, do not allow another */
2022   if (btm_cb.devcb.p_tx_power_cmpl_cb) return (BTM_BUSY);
2023
2024   p = btm_bda_to_acl(remote_bda, transport);
2025   if (p != (tACL_CONN*)NULL) {
2026     btm_cb.devcb.p_tx_power_cmpl_cb = p_cb;
2027     alarm_set_on_queue(btm_cb.devcb.read_tx_power_timer,
2028                        BTM_DEV_REPLY_TIMEOUT_MS, btm_read_tx_power_timeout,
2029                        NULL, btu_general_alarm_queue);
2030
2031     if (p->transport == BT_TRANSPORT_LE) {
2032       memcpy(btm_cb.devcb.read_tx_pwr_addr, remote_bda, BD_ADDR_LEN);
2033       btsnd_hcic_ble_read_adv_chnl_tx_power();
2034     } else {
2035       btsnd_hcic_read_tx_power(p->hci_handle, BTM_READ_RSSI_TYPE_CUR);
2036     }
2037
2038     return (BTM_CMD_STARTED);
2039   }
2040
2041   /* If here, no BD Addr found */
2042   return (BTM_UNKNOWN_ADDR);
2043 }
2044
2045 /*******************************************************************************
2046  *
2047  * Function         btm_read_tx_power_timeout
2048  *
2049  * Description      Callback when reading the tx power times out.
2050  *
2051  * Returns          void
2052  *
2053  ******************************************************************************/
2054 void btm_read_tx_power_timeout(UNUSED_ATTR void* data) {
2055   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_tx_power_cmpl_cb;
2056   btm_cb.devcb.p_tx_power_cmpl_cb = NULL;
2057   if (p_cb) (*p_cb)((void*)NULL);
2058 }
2059
2060 /*******************************************************************************
2061  *
2062  * Function         btm_read_tx_power_complete
2063  *
2064  * Description      This function is called when the command complete message
2065  *                  is received from the HCI for the read tx power request.
2066  *
2067  * Returns          void
2068  *
2069  ******************************************************************************/
2070 void btm_read_tx_power_complete(uint8_t* p, bool is_ble) {
2071   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_tx_power_cmpl_cb;
2072   tBTM_TX_POWER_RESULTS results;
2073   uint16_t handle;
2074   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2075   uint16_t index;
2076
2077   BTM_TRACE_DEBUG("%s", __func__);
2078   alarm_cancel(btm_cb.devcb.read_tx_power_timer);
2079   btm_cb.devcb.p_tx_power_cmpl_cb = NULL;
2080
2081   /* If there was a registered callback, call it */
2082   if (p_cb) {
2083     STREAM_TO_UINT8(results.hci_status, p);
2084
2085     if (results.hci_status == HCI_SUCCESS) {
2086       results.status = BTM_SUCCESS;
2087
2088       if (!is_ble) {
2089         STREAM_TO_UINT16(handle, p);
2090         STREAM_TO_UINT8(results.tx_power, p);
2091
2092         /* Search through the list of active channels for the correct BD Addr */
2093         for (index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2094           if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2095             memcpy(results.rem_bda, p_acl_cb->remote_addr, BD_ADDR_LEN);
2096             break;
2097           }
2098         }
2099       } else {
2100         STREAM_TO_UINT8(results.tx_power, p);
2101         memcpy(results.rem_bda, btm_cb.devcb.read_tx_pwr_addr, BD_ADDR_LEN);
2102       }
2103       BTM_TRACE_DEBUG("BTM TX power Complete: tx_power %d, hci status 0x%02x",
2104                       results.tx_power, results.hci_status);
2105     } else
2106       results.status = BTM_ERR_PROCESSING;
2107
2108     (*p_cb)(&results);
2109   }
2110 }
2111
2112 /*******************************************************************************
2113  *
2114  * Function         btm_read_rssi_timeout
2115  *
2116  * Description      Callback when reading the RSSI times out.
2117  *
2118  * Returns          void
2119  *
2120  ******************************************************************************/
2121 void btm_read_rssi_timeout(UNUSED_ATTR void* data) {
2122   tBTM_RSSI_RESULTS  results;
2123   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
2124   btm_cb.devcb.p_rssi_cmpl_cb = NULL;
2125   results.status = BTM_DEVICE_TIMEOUT;
2126   if (p_cb)
2127       (*p_cb)(&results);
2128 }
2129
2130 /*******************************************************************************
2131  *
2132  * Function         btm_read_rssi_complete
2133  *
2134  * Description      This function is called when the command complete message
2135  *                  is received from the HCI for the read rssi request.
2136  *
2137  * Returns          void
2138  *
2139  ******************************************************************************/
2140 void btm_read_rssi_complete(uint8_t* p) {
2141   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_rssi_cmpl_cb;
2142   tBTM_RSSI_RESULTS results;
2143   uint16_t handle;
2144   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2145   uint16_t index;
2146
2147   BTM_TRACE_DEBUG("%s", __func__);
2148   alarm_cancel(btm_cb.devcb.read_rssi_timer);
2149   btm_cb.devcb.p_rssi_cmpl_cb = NULL;
2150
2151   /* If there was a registered callback, call it */
2152   if (p_cb) {
2153     STREAM_TO_UINT8(results.hci_status, p);
2154
2155     if (results.hci_status == HCI_SUCCESS) {
2156       results.status = BTM_SUCCESS;
2157
2158       STREAM_TO_UINT16(handle, p);
2159
2160       STREAM_TO_UINT8(results.rssi, p);
2161       BTM_TRACE_DEBUG("BTM RSSI Complete: rssi %d, hci status 0x%02x",
2162                       results.rssi, results.hci_status);
2163
2164       /* Search through the list of active channels for the correct BD Addr */
2165       for (index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2166         if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2167           memcpy(results.rem_bda, p_acl_cb->remote_addr, BD_ADDR_LEN);
2168           break;
2169         }
2170       }
2171     } else
2172       results.status = BTM_ERR_PROCESSING;
2173
2174     (*p_cb)(&results);
2175   }
2176 }
2177
2178 /*******************************************************************************
2179  *
2180  * Function         btm_read_link_quality_timeout
2181  *
2182  * Description      Callback when reading the link quality times out.
2183  *
2184  * Returns          void
2185  *
2186  ******************************************************************************/
2187 void btm_read_link_quality_timeout(UNUSED_ATTR void* data) {
2188   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_link_qual_cmpl_cb;
2189   btm_cb.devcb.p_link_qual_cmpl_cb = NULL;
2190   if (p_cb) (*p_cb)((void*)NULL);
2191 }
2192
2193 /*******************************************************************************
2194  *
2195  * Function         btm_read_link_quality_complete
2196  *
2197  * Description      This function is called when the command complete message
2198  *                  is received from the HCI for the read link quality.
2199  *
2200  * Returns          void
2201  *
2202  ******************************************************************************/
2203 void btm_read_link_quality_complete(uint8_t* p) {
2204   tBTM_CMPL_CB* p_cb = btm_cb.devcb.p_link_qual_cmpl_cb;
2205   tBTM_LINK_QUALITY_RESULTS results;
2206   uint16_t handle;
2207   tACL_CONN* p_acl_cb = &btm_cb.acl_db[0];
2208   uint16_t index;
2209
2210   BTM_TRACE_DEBUG("%s", __func__);
2211   alarm_cancel(btm_cb.devcb.read_link_quality_timer);
2212   btm_cb.devcb.p_link_qual_cmpl_cb = NULL;
2213
2214   /* If there was a registered callback, call it */
2215   if (p_cb) {
2216     STREAM_TO_UINT8(results.hci_status, p);
2217
2218     if (results.hci_status == HCI_SUCCESS) {
2219       results.status = BTM_SUCCESS;
2220
2221       STREAM_TO_UINT16(handle, p);
2222
2223       STREAM_TO_UINT8(results.link_quality, p);
2224       BTM_TRACE_DEBUG(
2225           "BTM Link Quality Complete: Link Quality %d, hci status 0x%02x",
2226           results.link_quality, results.hci_status);
2227
2228       /* Search through the list of active channels for the correct BD Addr */
2229       for (index = 0; index < MAX_L2CAP_LINKS; index++, p_acl_cb++) {
2230         if ((p_acl_cb->in_use) && (handle == p_acl_cb->hci_handle)) {
2231           memcpy(results.rem_bda, p_acl_cb->remote_addr, BD_ADDR_LEN);
2232           break;
2233         }
2234       }
2235     } else
2236       results.status = BTM_ERR_PROCESSING;
2237
2238     (*p_cb)(&results);
2239   }
2240 }
2241
2242 /*******************************************************************************
2243  *
2244  * Function         btm_remove_acl
2245  *
2246  * Description      This function is called to disconnect an ACL connection
2247  *
2248  * Returns          BTM_SUCCESS if successfully initiated, otherwise
2249  *                  BTM_NO_RESOURCES.
2250  *
2251  ******************************************************************************/
2252 tBTM_STATUS btm_remove_acl(BD_ADDR bd_addr, tBT_TRANSPORT transport) {
2253   uint16_t hci_handle = BTM_GetHCIConnHandle(bd_addr, transport);
2254   tBTM_STATUS status = BTM_SUCCESS;
2255
2256   BTM_TRACE_DEBUG("btm_remove_acl");
2257 #if (BTM_DISC_DURING_RS == TRUE)
2258   tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
2259
2260   /* Role Switch is pending, postpone until completed */
2261   if (p_dev_rec && (p_dev_rec->rs_disc_pending == BTM_SEC_RS_PENDING)) {
2262     p_dev_rec->rs_disc_pending = BTM_SEC_DISC_PENDING;
2263   } else /* otherwise can disconnect right away */
2264 #endif
2265   {
2266     if (hci_handle != 0xFFFF && p_dev_rec &&
2267         p_dev_rec->sec_state != BTM_SEC_STATE_DISCONNECTING) {
2268       btsnd_hcic_disconnect(hci_handle, HCI_ERR_PEER_USER);
2269     } else
2270       status = BTM_UNKNOWN_ADDR;
2271   }
2272
2273   return status;
2274 }
2275
2276 /*******************************************************************************
2277  *
2278  * Function         BTM_SetTraceLevel
2279  *
2280  * Description      This function sets the trace level for BTM.  If called with
2281  *                  a value of 0xFF, it simply returns the current trace level.
2282  *
2283  * Returns          The new or current trace level
2284  *
2285  ******************************************************************************/
2286 uint8_t BTM_SetTraceLevel(uint8_t new_level) {
2287   BTM_TRACE_DEBUG("BTM_SetTraceLevel");
2288   if (new_level != 0xFF) btm_cb.trace_level = new_level;
2289
2290   return (btm_cb.trace_level);
2291 }
2292
2293 /*******************************************************************************
2294  *
2295  * Function         btm_cont_rswitch
2296  *
2297  * Description      This function is called to continue processing an active
2298  *                  role switch. It first disables encryption if enabled and
2299  *                  EPR is not supported
2300  *
2301  * Returns          void
2302  *
2303  ******************************************************************************/
2304 void btm_cont_rswitch(tACL_CONN* p, tBTM_SEC_DEV_REC* p_dev_rec,
2305                       uint8_t hci_status) {
2306   BTM_TRACE_DEBUG("btm_cont_rswitch");
2307   /* Check to see if encryption needs to be turned off if pending
2308      change of link key or role switch */
2309   if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE) {
2310     /* Must turn off Encryption first if necessary */
2311     /* Some devices do not support switch or change of link key while encryption
2312      * is on */
2313     if (p_dev_rec != NULL &&
2314         ((p_dev_rec->sec_flags & BTM_SEC_ENCRYPTED) != 0) &&
2315         !BTM_EPR_AVAILABLE(p)) {
2316       btsnd_hcic_set_conn_encrypt(p->hci_handle, false);
2317       p->encrypt_state = BTM_ACL_ENCRYPT_STATE_ENCRYPT_OFF;
2318       if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE)
2319         p->switch_role_state = BTM_ACL_SWKEY_STATE_ENCRYPTION_OFF;
2320     } else /* Encryption not used or EPR supported, continue with switch
2321               and/or change of link key */
2322     {
2323       if (p->switch_role_state == BTM_ACL_SWKEY_STATE_MODE_CHANGE) {
2324         p->switch_role_state = BTM_ACL_SWKEY_STATE_IN_PROGRESS;
2325 #if (BTM_DISC_DURING_RS == TRUE)
2326         if (p_dev_rec) p_dev_rec->rs_disc_pending = BTM_SEC_RS_PENDING;
2327 #endif
2328         btsnd_hcic_switch_role(p->remote_addr, (uint8_t)!p->link_role);
2329       }
2330     }
2331   }
2332 }
2333
2334 /*******************************************************************************
2335  *
2336  * Function         btm_acl_resubmit_page
2337  *
2338  * Description      send pending page request
2339  *
2340  ******************************************************************************/
2341 void btm_acl_resubmit_page(void) {
2342   tBTM_SEC_DEV_REC* p_dev_rec;
2343   BT_HDR* p_buf;
2344   uint8_t* pp;
2345   BD_ADDR bda;
2346   BTM_TRACE_DEBUG("btm_acl_resubmit_page");
2347   /* If there were other page request schedule can start the next one */
2348   p_buf = (BT_HDR*)fixed_queue_try_dequeue(btm_cb.page_queue);
2349   if (p_buf != NULL) {
2350     /* skip 3 (2 bytes opcode and 1 byte len) to get to the bd_addr
2351      * for both create_conn and rmt_name */
2352     pp = (uint8_t*)(p_buf + 1) + p_buf->offset + 3;
2353
2354     STREAM_TO_BDADDR(bda, pp);
2355
2356     p_dev_rec = btm_find_or_alloc_dev(bda);
2357
2358     memcpy(btm_cb.connecting_bda, p_dev_rec->bd_addr, BD_ADDR_LEN);
2359     memcpy(btm_cb.connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
2360
2361     btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p_buf);
2362   } else
2363     btm_cb.paging = false;
2364 }
2365
2366 /*******************************************************************************
2367  *
2368  * Function         btm_acl_reset_paging
2369  *
2370  * Description      set paging to false and free the page queue - called at
2371  *                  hci_reset
2372  *
2373  ******************************************************************************/
2374 void btm_acl_reset_paging(void) {
2375   BT_HDR* p;
2376   BTM_TRACE_DEBUG("btm_acl_reset_paging");
2377   /* If we sent reset we are definitely not paging any more */
2378   while ((p = (BT_HDR*)fixed_queue_try_dequeue(btm_cb.page_queue)) != NULL)
2379     osi_free(p);
2380
2381   btm_cb.paging = false;
2382 }
2383
2384 /*******************************************************************************
2385  *
2386  * Function         btm_acl_paging
2387  *
2388  * Description      send a paging command or queue it in btm_cb
2389  *
2390  ******************************************************************************/
2391 void btm_acl_paging(BT_HDR* p, BD_ADDR bda) {
2392   tBTM_SEC_DEV_REC* p_dev_rec;
2393
2394   BTM_TRACE_DEBUG("btm_acl_paging discing:%d, paging:%d BDA: %06x%06x",
2395                   btm_cb.discing, btm_cb.paging,
2396                   (bda[0] << 16) + (bda[1] << 8) + bda[2],
2397                   (bda[3] << 16) + (bda[4] << 8) + bda[5]);
2398   if (btm_cb.discing) {
2399     btm_cb.paging = true;
2400     fixed_queue_enqueue(btm_cb.page_queue, p);
2401   } else {
2402     if (!BTM_ACL_IS_CONNECTED(bda)) {
2403       BTM_TRACE_DEBUG(
2404           "connecting_bda: %06x%06x",
2405           (btm_cb.connecting_bda[0] << 16) + (btm_cb.connecting_bda[1] << 8) +
2406               btm_cb.connecting_bda[2],
2407           (btm_cb.connecting_bda[3] << 16) + (btm_cb.connecting_bda[4] << 8) +
2408               btm_cb.connecting_bda[5]);
2409       if (btm_cb.paging &&
2410           memcmp(bda, btm_cb.connecting_bda, BD_ADDR_LEN) != 0) {
2411         fixed_queue_enqueue(btm_cb.page_queue, p);
2412       } else {
2413         p_dev_rec = btm_find_or_alloc_dev(bda);
2414         memcpy(btm_cb.connecting_bda, p_dev_rec->bd_addr, BD_ADDR_LEN);
2415         memcpy(btm_cb.connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN);
2416
2417         btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
2418       }
2419
2420       btm_cb.paging = true;
2421     } else /* ACL is already up */
2422     {
2423       btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
2424     }
2425   }
2426 }
2427
2428 /*******************************************************************************
2429  *
2430  * Function         btm_acl_notif_conn_collision
2431  *
2432  * Description      Send connection collision event to upper layer if registered
2433  *
2434  * Returns          true if sent out to upper layer,
2435  *                  false if no one needs the notification.
2436  *
2437  ******************************************************************************/
2438 bool btm_acl_notif_conn_collision(BD_ADDR bda) {
2439   tBTM_BL_EVENT_DATA evt_data;
2440
2441   /* Report possible collision to the upper layer. */
2442   if (btm_cb.p_bl_changed_cb) {
2443     BTM_TRACE_DEBUG(
2444         "btm_acl_notif_conn_collision: RemBdAddr: %02x%02x%02x%02x%02x%02x",
2445         bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
2446
2447     evt_data.event = BTM_BL_COLLISION_EVT;
2448     evt_data.conn.p_bda = bda;
2449     evt_data.conn.transport = BT_TRANSPORT_BR_EDR;
2450     evt_data.conn.handle = BTM_INVALID_HCI_HANDLE;
2451     (*btm_cb.p_bl_changed_cb)(&evt_data);
2452     return true;
2453   } else
2454     return false;
2455 }
2456
2457 /*******************************************************************************
2458  *
2459  * Function         btm_acl_chk_peer_pkt_type_support
2460  *
2461  * Description      Check if peer supports requested packets
2462  *
2463  ******************************************************************************/
2464 void btm_acl_chk_peer_pkt_type_support(tACL_CONN* p, uint16_t* p_pkt_type) {
2465   /* 3 and 5 slot packets? */
2466   if (!HCI_3_SLOT_PACKETS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2467     *p_pkt_type &= ~(BTM_ACL_PKT_TYPES_MASK_DH3 + BTM_ACL_PKT_TYPES_MASK_DM3);
2468
2469   if (!HCI_5_SLOT_PACKETS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2470     *p_pkt_type &= ~(BTM_ACL_PKT_TYPES_MASK_DH5 + BTM_ACL_PKT_TYPES_MASK_DM5);
2471
2472   /* 2 and 3 MPS support? */
2473   if (!HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2474     /* Not supported. Add 'not_supported' mask for all 2MPS packet types */
2475     *p_pkt_type |=
2476         (BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 +
2477          BTM_ACL_PKT_TYPES_MASK_NO_2_DH5);
2478
2479   if (!HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_feature_pages[0]))
2480     /* Not supported. Add 'not_supported' mask for all 3MPS packet types */
2481     *p_pkt_type |=
2482         (BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 +
2483          BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
2484
2485   /* EDR 3 and 5 slot support? */
2486   if (HCI_EDR_ACL_2MPS_SUPPORTED(p->peer_lmp_feature_pages[0]) ||
2487       HCI_EDR_ACL_3MPS_SUPPORTED(p->peer_lmp_feature_pages[0])) {
2488     if (!HCI_3_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_feature_pages[0]))
2489       /* Not supported. Add 'not_supported' mask for all 3-slot EDR packet types
2490        */
2491       *p_pkt_type |=
2492           (BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH3);
2493
2494     if (!HCI_5_SLOT_EDR_ACL_SUPPORTED(p->peer_lmp_feature_pages[0]))
2495       /* Not supported. Add 'not_supported' mask for all 5-slot EDR packet types
2496        */
2497       *p_pkt_type |=
2498           (BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 + BTM_ACL_PKT_TYPES_MASK_NO_3_DH5);
2499   }
2500 }