1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <base/bind.h>
18 #include <base/location.h>
19 #include <base/strings/stringprintf.h>
20 #include <cstdint>
21 #include <memory>
22 
23 #include "device/include/interop.h"
24 #include "hci/controller.h"
25 #include "main/shim/controller.h"
26 #include "main/shim/dumpsys.h"
27 #include "main/shim/link_policy.h"
28 #include "main/shim/stack.h"
29 #include "osi/include/log.h"
30 #include "stack/btm/btm_int_types.h"
31 #include "stack/include/btm_api.h"
32 #include "stack/include/btm_api_types.h"
33 #include "stack/include/btm_ble_api_types.h"
34 #include "stack/include/hci_error_code.h"
35 #include "stack/include/hcidefs.h"
36 
37 bt_status_t do_in_main_thread(const base::Location& from_here,
38                               base::OnceClosure task);
39 
40 void btm_cont_rswitch_from_handle(uint16_t hci_handle);
41 void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle,
42                              tHCI_MODE mode, uint16_t interval);
43 void btm_sco_chk_pend_unpark(tHCI_STATUS hci_status, uint16_t hci_handle);
44 void l2c_OnHciModeChangeSendPendingPackets(RawAddress remote);
45 void process_ssr_event(tHCI_STATUS status, uint16_t handle,
46                        UNUSED_ATTR uint16_t max_tx_lat, uint16_t max_rx_lat);
47 tACL_CONN* acl_get_connection_from_handle(uint16_t handle);
48 
49 extern tBTM_CB btm_cb;
50 
51 namespace {
52 
set_active_mode(tACL_CONN & p_acl)53 tBTM_STATUS set_active_mode(tACL_CONN& p_acl) {
54   bluetooth::shim::Stack::GetInstance()->LinkPolicy()->ExitSniffMode(
55       p_acl.hci_handle);
56   return BTM_SUCCESS;
57 }
58 
set_hold_mode(tACL_CONN & p_acl,uint16_t max,uint16_t min)59 tBTM_STATUS set_hold_mode(tACL_CONN& p_acl, uint16_t max, uint16_t min) {
60   bluetooth::shim::Stack::GetInstance()->LinkPolicy()->HoldMode(
61       p_acl.hci_handle, max, min);
62   return BTM_SUCCESS;
63 }
64 
set_sniff_mode(tACL_CONN & p_acl,uint16_t max_interval,uint16_t min_interval,uint16_t attempt,uint16_t timeout)65 tBTM_STATUS set_sniff_mode(tACL_CONN& p_acl, uint16_t max_interval,
66                            uint16_t min_interval, uint16_t attempt,
67                            uint16_t timeout) {
68   bluetooth::shim::Stack::GetInstance()->LinkPolicy()->SniffMode(
69       p_acl.hci_handle, max_interval, min_interval, attempt, timeout);
70   return BTM_SUCCESS;
71 }
72 
controller_supports_link_policy_mode(const tBTM_PM_MODE & mode,bool interop_check)73 bool controller_supports_link_policy_mode(const tBTM_PM_MODE& mode,
74                                           bool interop_check) {
75   switch (mode) {
76     case BTM_PM_MD_ACTIVE:  // Active mode is always supported
77       break;
78     case BTM_PM_MD_PARK:  // Park mode no longer supported
79       return false;
80     case BTM_PM_MD_SNIFF:
81       if (!controller_get_interface()->supports_sniff_mode() || interop_check)
82         return false;
83       break;
84     case BTM_PM_MD_HOLD:
85       if (!controller_get_interface()->supports_hold_mode() || interop_check)
86         return false;
87       break;
88     default:
89       LOG_ERROR("Unknown mode:%u", mode);
90       return false;
91   }
92   return true;
93 }
94 
95 }  // namespace
96 
RegisterLinkPolicyClient(tBTM_PM_STATUS_CBACK * p_cb)97 bool bluetooth::shim::RegisterLinkPolicyClient(tBTM_PM_STATUS_CBACK* p_cb) {
98   if (std::find(btm_cb.acl_cb_.link_policy.clients.begin(),
99                 btm_cb.acl_cb_.link_policy.clients.end(),
100                 p_cb) != btm_cb.acl_cb_.link_policy.clients.end()) {
101     LOG_ERROR("Link policy client already registered");
102     return false;
103   }
104   btm_cb.acl_cb_.link_policy.clients.push_back(p_cb);
105   return true;
106 }
107 
UnregisterLinkPolicyClient(tBTM_PM_STATUS_CBACK * p_cb)108 bool bluetooth::shim::UnregisterLinkPolicyClient(tBTM_PM_STATUS_CBACK* p_cb) {
109   auto cb = std::find(btm_cb.acl_cb_.link_policy.clients.begin(),
110                       btm_cb.acl_cb_.link_policy.clients.end(), p_cb);
111   if (cb == btm_cb.acl_cb_.link_policy.clients.end()) {
112     LOG_ERROR("Link policy client already unregistered");
113     return false;
114   }
115   btm_cb.acl_cb_.link_policy.clients.erase(cb);
116   return true;
117 }
118 
BTM_SetPowerMode(uint16_t handle,const tBTM_PM_PWR_MD & new_mode)119 tBTM_STATUS bluetooth::shim::BTM_SetPowerMode(uint16_t handle,
120                                               const tBTM_PM_PWR_MD& new_mode) {
121   tACL_CONN* p_acl = acl_get_connection_from_handle(handle);
122   if (p_acl == nullptr) {
123     return BTM_UNKNOWN_ADDR;
124   }
125 
126   if (!controller_supports_link_policy_mode(
127           new_mode.mode,
128           interop_match_addr(INTEROP_DISABLE_SNIFF, &p_acl->remote_addr))) {
129     return BTM_MODE_UNSUPPORTED;
130   }
131 
132   if (p_acl->policy.Mode() == new_mode.mode) {
133     LOG_INFO("Controller already in mode:%s[0x%02x]",
134              power_mode_state_text(p_acl->policy.Mode()).c_str(),
135              p_acl->policy.Mode());
136   }
137 
138   if (p_acl->policy.mode.IsPending()) {
139     LOG_INFO("Link policy mode is pending");
140   }
141 
142   LOG_INFO("Switching mode from %s(0x%x) to %s(0x%x)",
143            power_mode_state_text(p_acl->policy.Mode()).c_str(),
144            p_acl->policy.Mode(), power_mode_state_text(new_mode.mode).c_str(),
145            new_mode.mode);
146 
147   p_acl->policy.mode.pending_ = new_mode.mode;
148   switch (new_mode.mode) {
149     case BTM_PM_MD_ACTIVE:
150       set_active_mode(*p_acl);
151       return BTM_SUCCESS;
152       break;
153     case BTM_PM_MD_SNIFF:
154       set_sniff_mode(*p_acl, new_mode.max, new_mode.min, new_mode.attempt,
155                      new_mode.timeout);
156       return BTM_SUCCESS;
157       break;
158     case BTM_PM_MD_HOLD:
159       return set_hold_mode(*p_acl, new_mode.max, new_mode.min);
160       break;
161   }
162   return BTM_MODE_UNSUPPORTED;
163 }
164 
is_encryption_pause_supported(const tACL_CONN & p_acl)165 static bool is_encryption_pause_supported(const tACL_CONN& p_acl) {
166   CHECK(p_acl.peer_lmp_feature_valid[0])
167       << "Checked before remote feature read has complete";
168   return HCI_ATOMIC_ENCRYPT_SUPPORTED(p_acl.peer_lmp_feature_pages[0]) &&
169          controller_get_interface()->supports_encryption_pause();
170 }
171 
btm_pm_on_mode_change(tHCI_STATUS status,uint16_t handle,tHCI_MODE hci_mode,uint16_t interval)172 void bluetooth::shim::btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle,
173                                             tHCI_MODE hci_mode,
174                                             uint16_t interval) {
175   tBTM_PM_MODE new_mode = HCI_TO_BTM_POWER_MODE(hci_mode);
176 
177   LOG_DEBUG(
178       "For now pointing back again to legacy status:%s handle:0x%04x "
179       "new_mode:%u interval:%u",
180       hci_error_code_text(status).c_str(), handle, new_mode, interval);
181 
182   tACL_CONN* p_acl = acl_get_connection_from_handle(handle);
183   if (p_acl == nullptr) {
184     LOG_ERROR("Received mode change for unknown acl handle:0x%04x", handle);
185     return;
186   }
187 
188   tBTM_PM_MODE pending = p_acl->policy.mode.Pending();
189   p_acl->policy.mode.pending_ = BTM_PM_MD_UNKNOWN;
190 
191   if (status == HCI_SUCCESS) {
192     BTM_LogHistory(
193         "Power", p_acl->remote_addr, "Mode change",
194         base::StringPrintf("%s[0x%02x] ==> %s[0x%02x] pending:%s",
195                            power_mode_state_text(p_acl->policy.Mode()).c_str(),
196                            p_acl->policy.Mode(),
197                            power_mode_state_text(new_mode).c_str(), new_mode,
198                            power_mode_state_text(pending).c_str()));
199     LOG_INFO("Power mode switched from %s[%hhu] to %s[%hhu] pending:%s",
200              power_mode_state_text(p_acl->policy.Mode()).c_str(),
201              p_acl->policy.Mode(), power_mode_state_text(new_mode).c_str(),
202              new_mode, power_mode_state_text(pending).c_str());
203     p_acl->policy.mode.mode_ = new_mode;
204 
205     if (new_mode == (BTM_PM_ST_ACTIVE) || new_mode == (BTM_PM_ST_SNIFF)) {
206       l2c_OnHciModeChangeSendPendingPackets(p_acl->remote_addr);
207     }
208 
209     /*check if sco disconnect  is waiting for the mode change */
210     btm_sco_disc_chk_pend_for_modechange(handle);
211 
212     if (p_acl->is_switch_role_mode_change()) {
213       if (p_acl->is_encrypted && !is_encryption_pause_supported(*p_acl)) {
214         p_acl->set_encryption_off();
215         p_acl->set_switch_role_encryption_off();
216       } else {
217         p_acl->set_switch_role_in_progress();
218         p_acl->rs_disc_pending = BTM_SEC_RS_PENDING;
219         bluetooth::legacy::hci::GetInterface().StartRoleSwitch(
220             p_acl->remote_addr, HCI_ROLE_CENTRAL);
221       }
222     }
223   }
224 
225   btm_sco_chk_pend_unpark(status, handle);
226   // btm_pm_proc_mode_change(status, handle, new_mode, interval);
227 
228   for (auto client_callback : btm_cb.acl_cb_.link_policy.clients) {
229     (*client_callback)(p_acl->remote_addr, new_mode, interval, status);
230   }
231 
232   LOG_DEBUG(
233       "Notified mode change registered clients cnt:%zu peer:%s "
234       "status:%s",
235       btm_cb.acl_cb_.link_policy.clients.size(),
236       PRIVATE_ADDRESS(p_acl->remote_addr), hci_error_code_text(status).c_str());
237 }
238 
BTM_SetSsrParams(uint16_t handle,uint16_t max_lat,uint16_t min_rmt_to,uint16_t min_loc_to)239 tBTM_STATUS bluetooth::shim::BTM_SetSsrParams(uint16_t handle, uint16_t max_lat,
240                                               uint16_t min_rmt_to,
241                                               uint16_t min_loc_to) {
242   LOG_DEBUG("Sending gd power mode SSR Params");
243   tACL_CONN* p_acl = acl_get_connection_from_handle(handle);
244   if (p_acl == nullptr) {
245     return BTM_UNKNOWN_ADDR;
246   }
247 
248   p_acl->policy.sniff_subrating.pending_ = true;
249   bluetooth::shim::Stack::GetInstance()->LinkPolicy()->SniffSubrating(
250       handle, max_lat, min_rmt_to, min_loc_to);
251   return BTM_SUCCESS;
252 }
253 
btm_pm_on_sniff_subrating(tHCI_STATUS status,uint16_t handle,uint16_t maximum_transmit_latency,UNUSED_ATTR uint16_t maximum_receive_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)254 void bluetooth::shim::btm_pm_on_sniff_subrating(
255     tHCI_STATUS status, uint16_t handle, uint16_t maximum_transmit_latency,
256     UNUSED_ATTR uint16_t maximum_receive_latency,
257     uint16_t minimum_remote_timeout, uint16_t minimum_local_timeout) {
258   LOG_DEBUG("For now pointing back again to legacy");
259   tACL_CONN* p_acl = acl_get_connection_from_handle(handle);
260   if (p_acl == nullptr) {
261     LOG_ERROR("Received mode change for unknown acl handle:0x%04x", handle);
262     return;
263   }
264 
265   p_acl->policy.sniff_subrating.pending_ = false;
266   if (status == HCI_SUCCESS) {
267     BTM_LogHistory(
268         "Power", p_acl->remote_addr, "Sniff Subrating",
269         base::StringPrintf(
270             "max_xmit_latency:%.2fs remote_timeout:%.2fs local_timeout:%.2fs",
271             ticks_to_seconds(maximum_transmit_latency),
272             ticks_to_seconds(minimum_remote_timeout),
273             ticks_to_seconds(minimum_local_timeout)));
274   }
275 
276   const bool use_ssr =
277       (p_acl->policy.mode.Interval() != maximum_receive_latency) ? true : false;
278 
279   for (auto client_callback : btm_cb.acl_cb_.link_policy.clients) {
280     (*client_callback)(p_acl->remote_addr, BTM_PM_STS_SSR, (use_ssr) ? 1 : 0,
281                        status);
282   }
283 
284   LOG_DEBUG(
285       "Notified sniff subrating registered clients cnt:%zu peer:%s use_ssr:%s "
286       "status:%s",
287       btm_cb.acl_cb_.link_policy.clients.size(),
288       PRIVATE_ADDRESS(p_acl->remote_addr), logbool(use_ssr).c_str(),
289       hci_error_code_text(status).c_str());
290 }
291