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