OSDN Git Service

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