1 /******************************************************************************
2  *
3  *  Copyright 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  *  This file contains functions that manages ACL link modes.
22  *  This includes operations such as active, hold,
23  *  park and sniff modes.
24  *
25  *  This module contains both internal and external (API)
26  *  functions. External (API) functions are distinguishable
27  *  by their names beginning with uppercase BTM.
28  *
29  *****************************************************************************/
30 
31 #include "main/shim/entry.h"
32 #define LOG_TAG "bt_btm_pm"
33 
34 #include <base/strings/stringprintf.h>
35 #include <bluetooth/log.h>
36 
37 #include <cstdint>
38 #include <unordered_map>
39 
40 #include "device/include/interop.h"
41 #include "hci/controller_interface.h"
42 #include "internal_include/bt_target.h"
43 #include "main/shim/dumpsys.h"
44 #include "main/shim/entry.h"
45 #include "os/log.h"
46 #include "osi/include/stack_power_telemetry.h"
47 #include "stack/btm/btm_int_types.h"
48 #include "stack/include/bt_types.h"
49 #include "stack/include/btm_log_history.h"
50 #include "stack/include/btm_status.h"
51 #include "types/raw_address.h"
52 
53 using namespace bluetooth;
54 
55 void l2c_OnHciModeChangeSendPendingPackets(RawAddress remote);
56 void btm_sco_chk_pend_unpark(tHCI_STATUS status, uint16_t handle);
57 void btm_cont_rswitch_from_handle(uint16_t hci_handle);
58 extern tBTM_CB btm_cb;
59 
60 namespace {
61 uint16_t pm_pend_link = 0;
62 
63 std::unordered_map<uint16_t /* handle */, tBTM_PM_MCB> pm_mode_db;
64 
btm_pm_get_power_manager_from_address(const RawAddress & bda)65 tBTM_PM_MCB* btm_pm_get_power_manager_from_address(const RawAddress& bda) {
66   for (auto& entry : pm_mode_db) {
67     if (entry.second.bda_ == bda) {
68       return &entry.second;
69     }
70   }
71   return nullptr;
72 }
73 
74 tBTM_PM_RCB pm_reg_db; /* per application/module */
75 
76 uint8_t pm_pend_id = 0; /* the id pf the module, which has a pending PM cmd */
77 
78 constexpr char kBtmLogTag[] = "ACL";
79 }
80 
81 /*****************************************************************************/
82 /*      to handle different modes                                            */
83 /*****************************************************************************/
84 #define BTM_PM_NUM_SET_MODES 3  /* only hold, sniff & park */
85 
86 #define BTM_PM_GET_MD1 1
87 #define BTM_PM_GET_MD2 2
88 #define BTM_PM_GET_COMP 3
89 
90 const uint8_t
91     btm_pm_md_comp_matrix[BTM_PM_NUM_SET_MODES * BTM_PM_NUM_SET_MODES] = {
92         BTM_PM_GET_COMP, BTM_PM_GET_MD2,  BTM_PM_GET_MD2,
93 
94         BTM_PM_GET_MD1,  BTM_PM_GET_COMP, BTM_PM_GET_MD1,
95 
96         BTM_PM_GET_MD1,  BTM_PM_GET_MD2,  BTM_PM_GET_COMP};
97 
send_sniff_subrating(uint16_t handle,const RawAddress & addr,uint16_t max_lat,uint16_t min_rmt_to,uint16_t min_loc_to)98 static void send_sniff_subrating(uint16_t handle, const RawAddress& addr,
99                                  uint16_t max_lat, uint16_t min_rmt_to,
100                                  uint16_t min_loc_to) {
101   uint16_t new_max_lat = 0;
102   if (interop_match_addr_get_max_lat(INTEROP_UPDATE_HID_SSR_MAX_LAT, &addr,
103                                      &new_max_lat)) {
104     max_lat = new_max_lat;
105   }
106 
107   btsnd_hcic_sniff_sub_rate(handle, max_lat, min_rmt_to, min_loc_to);
108   BTM_LogHistory(kBtmLogTag, addr, "Sniff subrating",
109                  base::StringPrintf(
110                      "max_latency:%.2f peer_timeout:%.2f local_timeout:%.2f",
111                      ticks_to_seconds(max_lat), ticks_to_seconds(min_rmt_to),
112                      ticks_to_seconds(min_loc_to)));
113 }
114 
115 static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id,
116                                      int link_ind,
117                                      const tBTM_PM_PWR_MD* p_mode);
118 
119 /*****************************************************************************/
120 /*                     P U B L I C  F U N C T I O N S                        */
121 /*****************************************************************************/
122 /*******************************************************************************
123  *
124  * Function         BTM_PmRegister
125  *
126  * Description      register or deregister with power manager
127  *
128  * Returns          BTM_SUCCESS if successful,
129  *                  BTM_NO_RESOURCES if no room to hold registration
130  *                  BTM_ILLEGAL_VALUE
131  *
132  ******************************************************************************/
BTM_PmRegister(uint8_t mask,uint8_t * p_pm_id,tBTM_PM_STATUS_CBACK * p_cb)133 tBTM_STATUS BTM_PmRegister(uint8_t mask, uint8_t* p_pm_id,
134                            tBTM_PM_STATUS_CBACK* p_cb) {
135   /* de-register */
136   if (mask & BTM_PM_DEREG) {
137     if (*p_pm_id >= BTM_MAX_PM_RECORDS) return BTM_ILLEGAL_VALUE;
138     pm_reg_db.mask = BTM_PM_REC_NOT_USED;
139     return BTM_SUCCESS;
140   }
141 
142   if (pm_reg_db.mask == BTM_PM_REC_NOT_USED) {
143     /* if register for notification, should provide callback routine */
144     if (p_cb == NULL) return BTM_ILLEGAL_VALUE;
145     pm_reg_db.cback = p_cb;
146     pm_reg_db.mask = mask;
147     *p_pm_id = 0;
148     return BTM_SUCCESS;
149   }
150 
151   return BTM_NO_RESOURCES;
152 }
153 
BTM_PM_OnConnected(uint16_t handle,const RawAddress & remote_bda)154 void BTM_PM_OnConnected(uint16_t handle, const RawAddress& remote_bda) {
155   if (pm_mode_db.find(handle) != pm_mode_db.end()) {
156     log::error("Overwriting power mode db entry handle:{} peer:{}", handle,
157                remote_bda);
158   }
159   pm_mode_db[handle] = {};
160   pm_mode_db[handle].Init(remote_bda, handle);
161 }
162 
BTM_PM_OnDisconnected(uint16_t handle)163 void BTM_PM_OnDisconnected(uint16_t handle) {
164   if (pm_mode_db.find(handle) == pm_mode_db.end()) {
165     log::error("Erasing unknown power mode db entry handle:{}", handle);
166   }
167   pm_mode_db.erase(handle);
168   if (handle == pm_pend_link) {
169     pm_pend_link = 0;
170   }
171 }
172 
173 /*******************************************************************************
174  *
175  * Function         BTM_SetPowerMode
176  *
177  * Description      store the mode in control block or
178  *                  alter ACL connection behavior.
179  *
180  * Returns          BTM_SUCCESS if successful,
181  *                  BTM_UNKNOWN_ADDR if bd addr is not active or bad
182  *
183  ******************************************************************************/
BTM_SetPowerMode(uint8_t pm_id,const RawAddress & remote_bda,const tBTM_PM_PWR_MD * p_mode)184 tBTM_STATUS BTM_SetPowerMode(uint8_t pm_id, const RawAddress& remote_bda,
185                              const tBTM_PM_PWR_MD* p_mode) {
186   if (pm_id >= BTM_MAX_PM_RECORDS) {
187     pm_id = BTM_PM_SET_ONLY_ID;
188   }
189 
190   if (!p_mode) {
191     log::error("pm_id: {}, p_mode is null for {}", unsigned(pm_id), remote_bda);
192     return BTM_ILLEGAL_VALUE;
193   }
194 
195   // per ACL link
196   auto* p_cb = btm_pm_get_power_manager_from_address(remote_bda);
197   if (p_cb == nullptr) {
198     log::warn("Unable to find power manager for peer: {}", remote_bda);
199     return BTM_UNKNOWN_ADDR;
200   }
201   uint16_t handle = p_cb->handle_;
202 
203   tBTM_PM_MODE mode = p_mode->mode;
204   if (!is_legal_power_mode(mode)) {
205     log::error("Unable to set illegal power mode value:0x{:02x}", mode);
206     return BTM_ILLEGAL_VALUE;
207   }
208 
209   if (p_mode->mode & BTM_PM_MD_FORCE) {
210     log::info("Attempting to force into this power mode");
211     /* take out the force bit */
212     mode &= (~BTM_PM_MD_FORCE);
213   }
214 
215   if (mode != BTM_PM_MD_ACTIVE) {
216     auto controller = bluetooth::shim::GetController();
217     if ((mode == BTM_PM_MD_HOLD && !controller->SupportsHoldMode()) ||
218         (mode == BTM_PM_MD_SNIFF && !controller->SupportsSniffMode()) ||
219         (mode == BTM_PM_MD_PARK && !controller->SupportsParkMode()) ||
220         interop_match_addr(INTEROP_DISABLE_SNIFF, &remote_bda)) {
221       log::error("pm_id {} mode {} is not supported for {}", pm_id, mode,
222                  remote_bda);
223       return BTM_MODE_UNSUPPORTED;
224     }
225   }
226 
227   if (mode == p_cb->state) {
228     /* already in the requested mode and the current interval has less latency
229      * than the max */
230     if ((mode == BTM_PM_MD_ACTIVE) ||
231         ((p_mode->mode & BTM_PM_MD_FORCE) && (p_mode->max >= p_cb->interval) &&
232          (p_mode->min <= p_cb->interval)) ||
233         ((p_mode->mode & BTM_PM_MD_FORCE) == 0 &&
234          (p_mode->max >= p_cb->interval))) {
235       log::debug(
236           "Device is already in requested mode {}, interval: {}, max: {}, min: "
237           "{}",
238           p_mode->mode, p_cb->interval, p_mode->max, p_mode->min);
239       return BTM_SUCCESS;
240     }
241   }
242 
243   /* update mode database */
244   if (((pm_id != BTM_PM_SET_ONLY_ID) && (pm_reg_db.mask & BTM_PM_REG_SET)) ||
245       ((pm_id == BTM_PM_SET_ONLY_ID) && (pm_pend_link != 0))) {
246     /* Make sure mask is set to BTM_PM_REG_SET */
247     pm_reg_db.mask |= BTM_PM_REG_SET;
248     *(&p_cb->req_mode) = *p_mode;
249     p_cb->chg_ind = true;
250   }
251 
252   /* if mode == hold or pending, return */
253   if ((p_cb->state == BTM_PM_STS_HOLD) || (p_cb->state == BTM_PM_STS_PENDING) ||
254       (pm_pend_link != 0)) {
255     log::info(
256         "Current power mode is hold or pending status or pending links "
257         "state:{}[{}] pm_pending_link:{}",
258         power_mode_state_text(p_cb->state), p_cb->state, pm_pend_link);
259     /* command pending */
260     if (handle != pm_pend_link) {
261       p_cb->state |= BTM_PM_STORED_MASK;
262       log::info("Setting stored bitmask for peer:{}", remote_bda);
263     }
264     return BTM_CMD_STORED;
265   }
266 
267   log::info(
268       "Setting power mode for peer:{} current_mode:{}[{}] new_mode:{}[{}]",
269       remote_bda, power_mode_state_text(p_cb->state), p_cb->state,
270       power_mode_text(p_mode->mode), p_mode->mode);
271 
272   return btm_pm_snd_md_req(p_cb->handle_, pm_id, p_cb->handle_, p_mode);
273 }
274 
BTM_SetLinkPolicyActiveMode(const RawAddress & remote_bda)275 bool BTM_SetLinkPolicyActiveMode(const RawAddress& remote_bda) {
276   tBTM_PM_PWR_MD settings;
277   memset((void*)&settings, 0, sizeof(settings));
278   settings.mode = BTM_PM_MD_ACTIVE;
279 
280   switch (BTM_SetPowerMode(BTM_PM_SET_ONLY_ID, remote_bda, &settings)) {
281     case BTM_CMD_STORED:
282     case BTM_SUCCESS:
283       return true;
284     default:
285       return false;
286   }
287 }
288 
BTM_ReadPowerMode(const RawAddress & remote_bda,tBTM_PM_MODE * p_mode)289 bool BTM_ReadPowerMode(const RawAddress& remote_bda, tBTM_PM_MODE* p_mode) {
290   if (p_mode == nullptr) {
291     log::error("power mode is nullptr");
292     return false;
293   }
294   tBTM_PM_MCB* p_mcb = btm_pm_get_power_manager_from_address(remote_bda);
295   if (p_mcb == nullptr) {
296     log::warn("Unknown device:{}", remote_bda);
297     return false;
298   }
299   *p_mode = static_cast<tBTM_PM_MODE>(p_mcb->state);
300   return true;
301 }
302 
303 /*******************************************************************************
304  *
305  * Function         BTM_SetSsrParams
306  *
307  * Description      This sends the given SSR parameters for the given ACL
308  *                  connection if it is in ACTIVE mode.
309  *
310  * Input Param      remote_bda - device address of desired ACL connection
311  *                  max_lat    - maximum latency (in 0.625ms)(0-0xFFFE)
312  *                  min_rmt_to - minimum remote timeout
313  *                  min_loc_to - minimum local timeout
314  *
315  *
316  * Returns          BTM_SUCCESS if the HCI command is issued successful,
317  *                  BTM_UNKNOWN_ADDR if bd addr is not active or bad
318  *                  BTM_CMD_STORED if the command is stored
319  *
320  ******************************************************************************/
BTM_SetSsrParams(const RawAddress & remote_bda,uint16_t max_lat,uint16_t min_rmt_to,uint16_t min_loc_to)321 tBTM_STATUS BTM_SetSsrParams(const RawAddress& remote_bda, uint16_t max_lat,
322                              uint16_t min_rmt_to, uint16_t min_loc_to) {
323   tBTM_PM_MCB* p_cb = btm_pm_get_power_manager_from_address(remote_bda);
324   if (p_cb == nullptr) {
325     log::warn("Unable to find power manager for peer:{}", remote_bda);
326     return BTM_UNKNOWN_ADDR;
327   }
328 
329   if (!bluetooth::shim::GetController()->SupportsSniffSubrating()) {
330     log::info("No controller support for sniff subrating");
331     return BTM_SUCCESS;
332   }
333 
334   if (p_cb->state == BTM_PM_ST_ACTIVE || p_cb->state == BTM_PM_ST_SNIFF) {
335     log::info(
336         "Set sniff subrating state:{}[{}] max_latency:0x{:04x} "
337         "min_remote_timeout:0x{:04x} min_local_timeout:0x{:04x}",
338         power_mode_state_text(p_cb->state), p_cb->state, max_lat, min_rmt_to,
339         min_loc_to);
340     send_sniff_subrating(p_cb->handle_, remote_bda, max_lat, min_rmt_to,
341                          min_loc_to);
342     return BTM_SUCCESS;
343   }
344   log::info("pm_mode_db state: {}", p_cb->state);
345   p_cb->max_lat = max_lat;
346   p_cb->min_rmt_to = min_rmt_to;
347   p_cb->min_loc_to = min_loc_to;
348   return BTM_CMD_STORED;
349 }
350 
351 /*******************************************************************************
352  *
353  * Function         btm_pm_reset
354  *
355  * Description      as a part of the BTM reset process.
356  *
357  * Returns          void
358  *
359  ******************************************************************************/
btm_pm_reset(void)360 void btm_pm_reset(void) {
361   tBTM_PM_STATUS_CBACK* cb = NULL;
362 
363   /* clear the pending request for application */
364   if ((pm_pend_id != BTM_PM_SET_ONLY_ID) && (pm_reg_db.mask & BTM_PM_REG_SET)) {
365     cb = pm_reg_db.cback;
366   }
367 
368   pm_reg_db.mask = BTM_PM_REC_NOT_USED;
369 
370   if (cb != NULL && pm_pend_link != 0) {
371     const RawAddress raw_address = pm_mode_db[pm_pend_link].bda_;
372     (*cb)(raw_address, BTM_PM_STS_ERROR, BTM_DEV_RESET, HCI_SUCCESS);
373   }
374   /* no command pending */
375   pm_pend_link = 0;
376   pm_mode_db.clear();
377   pm_pend_id = 0;
378   memset(&pm_reg_db, 0, sizeof(pm_reg_db));
379   log::info("reset pm");
380 }
381 
382 /*******************************************************************************
383  *
384  * Function     btm_pm_compare_modes
385  * Description  get the "more active" mode of the 2
386  * Returns      void
387  *
388  ******************************************************************************/
btm_pm_compare_modes(const tBTM_PM_PWR_MD * p_md1,const tBTM_PM_PWR_MD * p_md2,tBTM_PM_PWR_MD * p_res)389 static tBTM_PM_PWR_MD* btm_pm_compare_modes(const tBTM_PM_PWR_MD* p_md1,
390                                             const tBTM_PM_PWR_MD* p_md2,
391                                             tBTM_PM_PWR_MD* p_res) {
392   uint8_t res;
393 
394   if (p_md1 == NULL) {
395     *p_res = *p_md2;
396     p_res->mode &= ~BTM_PM_MD_FORCE;
397 
398     return p_res;
399   }
400 
401   if (p_md2->mode == BTM_PM_MD_ACTIVE || p_md1->mode == BTM_PM_MD_ACTIVE) {
402     return NULL;
403   }
404 
405   /* check if force bit is involved */
406   if (p_md1->mode & BTM_PM_MD_FORCE) {
407     *p_res = *p_md1;
408     p_res->mode &= ~BTM_PM_MD_FORCE;
409     return p_res;
410   }
411 
412   if (p_md2->mode & BTM_PM_MD_FORCE) {
413     *p_res = *p_md2;
414     p_res->mode &= ~BTM_PM_MD_FORCE;
415     return p_res;
416   }
417 
418   res = (p_md1->mode - 1) * BTM_PM_NUM_SET_MODES + (p_md2->mode - 1);
419   res = btm_pm_md_comp_matrix[res];
420   switch (res) {
421     case BTM_PM_GET_MD1:
422       *p_res = *p_md1;
423       return p_res;
424 
425     case BTM_PM_GET_MD2:
426       *p_res = *p_md2;
427       return p_res;
428 
429     case BTM_PM_GET_COMP:
430       p_res->mode = p_md1->mode;
431       /* min of the two */
432       p_res->max = (p_md1->max < p_md2->max) ? (p_md1->max) : (p_md2->max);
433       /* max of the two */
434       p_res->min = (p_md1->min > p_md2->min) ? (p_md1->min) : (p_md2->min);
435 
436       /* the intersection is NULL */
437       if (p_res->max < p_res->min) return NULL;
438 
439       if (p_res->mode == BTM_PM_MD_SNIFF) {
440         /* max of the two */
441         p_res->attempt = (p_md1->attempt > p_md2->attempt) ? (p_md1->attempt)
442                                                            : (p_md2->attempt);
443         p_res->timeout = (p_md1->timeout > p_md2->timeout) ? (p_md1->timeout)
444                                                            : (p_md2->timeout);
445       }
446       return p_res;
447   }
448   return NULL;
449 }
450 
451 /*******************************************************************************
452  *
453  * Function     btm_pm_get_set_mode
454  * Description  get the resulting mode from the registered parties, then compare
455  *              it with the requested mode, if the command is from an
456  *              unregistered party.
457  *
458  * Returns      void
459  *
460  ******************************************************************************/
btm_pm_get_set_mode(uint8_t pm_id,tBTM_PM_MCB * p_cb,const tBTM_PM_PWR_MD * p_mode,tBTM_PM_PWR_MD * p_res)461 static tBTM_PM_MODE btm_pm_get_set_mode(uint8_t pm_id, tBTM_PM_MCB* p_cb,
462                                         const tBTM_PM_PWR_MD* p_mode,
463                                         tBTM_PM_PWR_MD* p_res) {
464   tBTM_PM_PWR_MD* p_md = NULL;
465 
466   if (p_mode != NULL && p_mode->mode & BTM_PM_MD_FORCE) {
467     *p_res = *p_mode;
468     p_res->mode &= ~BTM_PM_MD_FORCE;
469     return p_res->mode;
470   }
471 
472   /* g through all the registered "set" parties */
473   if (pm_reg_db.mask & BTM_PM_REG_SET) {
474     if (p_cb->req_mode.mode == BTM_PM_MD_ACTIVE) {
475       /* if at least one registered (SET) party says ACTIVE, stay active */
476       return BTM_PM_MD_ACTIVE;
477     } else {
478       /* if registered parties give conflicting information, stay active */
479       if ((btm_pm_compare_modes(p_md, &p_cb->req_mode, p_res)) == NULL)
480         return BTM_PM_MD_ACTIVE;
481       p_md = p_res;
482     }
483   }
484 
485   /* if the resulting mode is NULL(nobody registers SET), use the requested mode
486    */
487   if (p_md == NULL) {
488     if (p_mode)
489       *p_res = *((tBTM_PM_PWR_MD*)p_mode);
490     else /* p_mode is NULL when btm_pm_snd_md_req is called from
491             btm_pm_proc_mode_change */
492       return BTM_PM_MD_ACTIVE;
493   } else {
494     /* if the command is from unregistered party,
495        compare the resulting mode from registered party*/
496     if ((pm_id == BTM_PM_SET_ONLY_ID) &&
497         ((btm_pm_compare_modes(p_mode, p_md, p_res)) == NULL))
498       return BTM_PM_MD_ACTIVE;
499   }
500 
501   return p_res->mode;
502 }
503 
504 /*******************************************************************************
505  *
506  * Function     btm_pm_snd_md_req
507  * Description  get the resulting mode and send the resuest to host controller
508  * Returns      tBTM_STATUS
509  *, bool    *p_chg_ind
510  ******************************************************************************/
btm_pm_snd_md_req(uint16_t handle,uint8_t pm_id,int link_ind,const tBTM_PM_PWR_MD * p_mode)511 static tBTM_STATUS btm_pm_snd_md_req(uint16_t handle, uint8_t pm_id,
512                                      int link_ind,
513                                      const tBTM_PM_PWR_MD* p_mode) {
514   log::assert_that(pm_mode_db.count(handle) != 0,
515                    "Unable to find active acl for handle {}", handle);
516   tBTM_PM_PWR_MD md_res;
517   tBTM_PM_MODE mode;
518   tBTM_PM_MCB* p_cb = &pm_mode_db[handle];
519   bool chg_ind = false;
520 
521   mode = btm_pm_get_set_mode(pm_id, p_cb, p_mode, &md_res);
522   md_res.mode = mode;
523 
524   log::verbose("Found controller in mode:{}", power_mode_text(mode));
525 
526   if (p_cb->state == mode) {
527     log::info("Link already in requested mode pm_id:{} link_ind:{} mode:{}[{}]",
528               pm_id, link_ind, power_mode_text(mode), mode);
529 
530     /* already in the resulting mode */
531     if ((mode == BTM_PM_MD_ACTIVE) ||
532         ((md_res.max >= p_cb->interval) && (md_res.min <= p_cb->interval))) {
533       log::debug("Storing command");
534       return BTM_CMD_STORED;
535     }
536     log::debug("Need to wake then sleep");
537     chg_ind = true;
538   }
539   p_cb->chg_ind = chg_ind;
540 
541   /* cannot go directly from current mode to resulting mode. */
542   if (mode != BTM_PM_MD_ACTIVE && p_cb->state != BTM_PM_MD_ACTIVE) {
543     log::debug("Power mode change delay required");
544     p_cb->chg_ind = true; /* needs to wake, then sleep */
545   }
546 
547   if (p_cb->chg_ind) {
548     log::debug("Need to wake first");
549     md_res.mode = BTM_PM_MD_ACTIVE;
550   } else if (BTM_PM_MD_SNIFF == md_res.mode && p_cb->max_lat) {
551     if (bluetooth::shim::GetController()->SupportsSniffSubrating()) {
552       log::debug("Sending sniff subrating to controller");
553       send_sniff_subrating(handle, p_cb->bda_, p_cb->max_lat, p_cb->min_rmt_to,
554                            p_cb->min_loc_to);
555     }
556     p_cb->max_lat = 0;
557   }
558   /* Default is failure */
559   pm_pend_link = 0;
560 
561   /* send the appropriate HCI command */
562   pm_pend_id = pm_id;
563 
564   log::info("Switching from {}[0x{:02x}] to {}[0x{:02x}]",
565             power_mode_state_text(p_cb->state), p_cb->state,
566             power_mode_state_text(md_res.mode), md_res.mode);
567   BTM_LogHistory(kBtmLogTag, p_cb->bda_, "Power mode change",
568                  base::StringPrintf(
569                      "%s[0x%02x] ==> %s[0x%02x]",
570                      power_mode_state_text(p_cb->state).c_str(), p_cb->state,
571                      power_mode_state_text(md_res.mode).c_str(), md_res.mode));
572 
573   switch (md_res.mode) {
574     case BTM_PM_MD_ACTIVE:
575       switch (p_cb->state) {
576         case BTM_PM_MD_SNIFF:
577           btsnd_hcic_exit_sniff_mode(handle);
578           pm_pend_link = handle;
579           break;
580         case BTM_PM_MD_PARK:
581           btsnd_hcic_exit_park_mode(handle);
582           pm_pend_link = handle;
583           break;
584         default:
585           /* Failure pm_pend_link = MAX_L2CAP_LINKS */
586           break;
587       }
588       break;
589 
590     case BTM_PM_MD_HOLD:
591       btsnd_hcic_hold_mode(handle, md_res.max, md_res.min);
592       pm_pend_link = handle;
593       break;
594 
595     case BTM_PM_MD_SNIFF:
596       btsnd_hcic_sniff_mode(handle, md_res.max, md_res.min, md_res.attempt,
597                             md_res.timeout);
598       pm_pend_link = handle;
599       break;
600 
601     case BTM_PM_MD_PARK:
602       btsnd_hcic_park_mode(handle, md_res.max, md_res.min);
603       pm_pend_link = handle;
604       break;
605     default:
606       /* Failure pm_pend_link = MAX_L2CAP_LINKS */
607       break;
608   }
609 
610   if (pm_pend_link == 0) {
611     /* the command was not sent */
612     log::error("pm_pending_link maxed out");
613     return (BTM_NO_RESOURCES);
614   }
615 
616   return BTM_CMD_STARTED;
617 }
618 
btm_pm_continue_pending_mode_changes()619 static void btm_pm_continue_pending_mode_changes() {
620   for (auto& entry : pm_mode_db) {
621     if (entry.second.state & BTM_PM_STORED_MASK) {
622       entry.second.state &= ~BTM_PM_STORED_MASK;
623       log::info("Found another link requiring power mode change:{}",
624                 entry.second.bda_);
625       btm_pm_snd_md_req(entry.second.handle_, BTM_PM_SET_ONLY_ID,
626                         entry.second.handle_, NULL);
627       return;
628     }
629   }
630 }
631 
632 /*******************************************************************************
633  *
634  * Function         btm_pm_proc_cmd_status
635  *
636  * Description      This function is called when an HCI command status event
637  *                  occurs for power manager related commands.
638  *
639  * Input Parms      status - status of the event (HCI_SUCCESS if no errors)
640  *
641  * Returns          none.
642  *
643  ******************************************************************************/
btm_pm_proc_cmd_status(tHCI_STATUS status)644 void btm_pm_proc_cmd_status(tHCI_STATUS status) {
645   if (pm_pend_link == 0) {
646     log::error(
647         "There are no links pending power mode changes; try to find other "
648         "pending changes");
649     btm_pm_continue_pending_mode_changes();
650     return;
651   }
652   if (pm_mode_db.count(pm_pend_link) == 0) {
653     log::error(
654         "Got PM change status for disconnected link {}; forgot to clean up "
655         "pm_pend_link?",
656         pm_pend_link);
657     btm_pm_continue_pending_mode_changes();
658     return;
659   }
660 
661   tBTM_PM_MCB* p_cb = &pm_mode_db[pm_pend_link];
662 
663   // if the command was not successful. Stay in the same state
664   tBTM_PM_STATUS pm_status = BTM_PM_STS_ERROR;
665 
666   if (status == HCI_SUCCESS) {
667     p_cb->state = BTM_PM_ST_PENDING;
668     pm_status = BTM_PM_STS_PENDING;
669   }
670 
671   /* notify the caller is appropriate */
672   if ((pm_pend_id != BTM_PM_SET_ONLY_ID) && (pm_reg_db.mask & BTM_PM_REG_SET)) {
673     const RawAddress bd_addr = pm_mode_db[pm_pend_link].bda_;
674     log::verbose("Notifying callback that link power mode is complete peer:{}",
675                  bd_addr);
676     (*pm_reg_db.cback)(bd_addr, pm_status, 0, status);
677   }
678 
679   log::verbose("Clearing pending power mode link state:{}",
680                power_mode_state_text(p_cb->state));
681   pm_pend_link = 0;
682 
683   btm_pm_continue_pending_mode_changes();
684 }
685 
686 /*******************************************************************************
687  *
688  * Function         btm_process_mode_change
689  *
690  * Description      This function is called when an HCI mode change event
691  *                  occurs.
692  *
693  * Input Parms      hci_status - status of the event (HCI_SUCCESS if no errors)
694  *                  hci_handle - connection handle associated with the change
695  *                  mode - HCI_MODE_ACTIVE, HCI_MODE_HOLD, HCI_MODE_SNIFF, or
696  *                         HCI_MODE_PARK
697  *                  interval - number of baseband slots (meaning depends on
698  *                                                       mode)
699  *
700  * Returns          none.
701  *
702  ******************************************************************************/
btm_pm_proc_mode_change(tHCI_STATUS hci_status,uint16_t hci_handle,tHCI_MODE hci_mode,uint16_t interval)703 void btm_pm_proc_mode_change(tHCI_STATUS hci_status, uint16_t hci_handle,
704                              tHCI_MODE hci_mode, uint16_t interval) {
705   tBTM_PM_STATUS mode = static_cast<tBTM_PM_STATUS>(hci_mode);
706 
707   /* update control block */
708   if (pm_mode_db.count(hci_handle) == 0) {
709     log::warn("Unable to find active acl for handle {}", hci_handle);
710     return;
711   }
712   tBTM_PM_MCB* p_cb = &pm_mode_db[hci_handle];
713 
714   const tBTM_PM_STATE old_state = p_cb->state;
715   p_cb->state = mode;
716   p_cb->interval = interval;
717 
718   log::info("Power mode switched from {}[{}] to {}[{}]",
719             power_mode_state_text(old_state), old_state,
720             power_mode_state_text(p_cb->state), p_cb->state);
721 
722   if ((p_cb->state == BTM_PM_ST_ACTIVE) || (p_cb->state == BTM_PM_ST_SNIFF)) {
723     l2c_OnHciModeChangeSendPendingPackets(p_cb->bda_);
724   }
725 
726   (mode != BTM_PM_ST_ACTIVE)
727       ? power_telemetry::GetInstance().LogSniffStarted(hci_handle, p_cb->bda_)
728       : power_telemetry::GetInstance().LogSniffStopped(hci_handle, p_cb->bda_);
729 
730   /* set req_mode  HOLD mode->ACTIVE */
731   if ((mode == BTM_PM_MD_ACTIVE) && (p_cb->req_mode.mode == BTM_PM_MD_HOLD))
732     p_cb->req_mode.mode = BTM_PM_MD_ACTIVE;
733 
734   /* new request has been made. - post a message to BTU task */
735   if (old_state & BTM_PM_STORED_MASK) {
736     btm_pm_snd_md_req(hci_handle, BTM_PM_SET_ONLY_ID, hci_handle, NULL);
737   } else {
738     for (auto& entry : pm_mode_db) {
739       if (entry.second.chg_ind) {
740         btm_pm_snd_md_req(entry.second.handle_, BTM_PM_SET_ONLY_ID,
741                           entry.second.handle_, NULL);
742         break;
743       }
744     }
745   }
746 
747   /* notify registered parties */
748   if (pm_reg_db.mask & BTM_PM_REG_SET) {
749     (*pm_reg_db.cback)(p_cb->bda_, mode, interval, hci_status);
750   }
751   /*check if sco disconnect  is waiting for the mode change */
752   btm_sco_disc_chk_pend_for_modechange(hci_handle);
753 
754   /* If mode change was because of an active role switch or change link key */
755   btm_cont_rswitch_from_handle(hci_handle);
756 }
757 
758 /*******************************************************************************
759  *
760  * Function         btm_pm_proc_ssr_evt
761  *
762  * Description      This function is called when an HCI sniff subrating event
763  *                  occurs.
764  *
765  * Returns          none.
766  *
767  ******************************************************************************/
process_ssr_event(tHCI_STATUS status,uint16_t handle,uint16_t,uint16_t max_rx_lat)768 void process_ssr_event(tHCI_STATUS status, uint16_t handle,
769                        uint16_t /* max_tx_lat */, uint16_t max_rx_lat) {
770   if (pm_mode_db.count(handle) == 0) {
771     log::warn("Received sniff subrating event with no active ACL");
772     return;
773   }
774   tBTM_PM_MCB* p_cb = &pm_mode_db[handle];
775   auto bd_addr = p_cb->bda_;
776 
777   bool use_ssr = true;
778   if (p_cb->interval == max_rx_lat) {
779     log::verbose(
780         "Sniff subrating unsupported so dropping to legacy sniff mode");
781     use_ssr = false;
782   } else {
783     log::verbose("Sniff subrating enabled");
784   }
785 
786   int cnt = 0;
787   if (pm_reg_db.mask & BTM_PM_REG_SET) {
788     (*pm_reg_db.cback)(bd_addr, BTM_PM_STS_SSR, (use_ssr) ? 1 : 0, status);
789     cnt++;
790   }
791   log::debug(
792       "Notified sniff subrating registered clients cnt:{} peer:{} use_ssr:{} "
793       "status:{}",
794       cnt, bd_addr, use_ssr, hci_error_code_text(status));
795 }
796 
btm_pm_on_sniff_subrating(tHCI_STATUS status,uint16_t handle,uint16_t maximum_transmit_latency,uint16_t maximum_receive_latency,uint16_t,uint16_t)797 void btm_pm_on_sniff_subrating(tHCI_STATUS status, uint16_t handle,
798                                uint16_t maximum_transmit_latency,
799                                uint16_t maximum_receive_latency,
800                                uint16_t /* minimum_remote_timeout */,
801                                uint16_t /* minimum_local_timeout */) {
802   process_ssr_event(status, handle, maximum_transmit_latency,
803                     maximum_receive_latency);
804 }
805 
btm_pm_proc_ssr_evt(uint8_t * p,uint16_t)806 void btm_pm_proc_ssr_evt(uint8_t* p, uint16_t /* evt_len */) {
807   uint8_t status;
808   uint16_t handle;
809   uint16_t max_tx_lat;
810   uint16_t max_rx_lat;
811 
812   STREAM_TO_UINT8(status, p);
813   STREAM_TO_UINT16(handle, p);
814   STREAM_TO_UINT16(max_tx_lat, p);
815   STREAM_TO_UINT16(max_rx_lat, p);
816 
817   process_ssr_event(static_cast<tHCI_STATUS>(status), handle, max_tx_lat,
818                     max_rx_lat);
819 }
820 
821 /*******************************************************************************
822  *
823  * Function         btm_pm_device_in_active_or_sniff_mode
824  *
825  * Description      This function is called to check if in active or sniff mode
826  *
827  * Returns          true, if in active or sniff mode
828  *
829  ******************************************************************************/
btm_pm_device_in_active_or_sniff_mode(void)830 static bool btm_pm_device_in_active_or_sniff_mode(void) {
831   /* The active state is the highest state-includes connected device and sniff
832    * mode*/
833 
834   /* Covers active and sniff modes */
835   if (!pm_mode_db.empty()) {
836     return true;
837   }
838 
839   /* Check BLE states */
840   if (!btm_cb.ble_ctr_cb.is_connection_state_idle()) {
841     log::verbose("- BLE state is not idle");
842     return true;
843   }
844 
845   return false;
846 }
847 
848 /*******************************************************************************
849  *
850  * Function         BTM_PM_DeviceInScanState
851  *
852  * Description      This function is called to check if in inquiry
853  *
854  * Returns          true, if in inquiry
855  *
856  ******************************************************************************/
BTM_PM_DeviceInScanState(void)857 bool BTM_PM_DeviceInScanState(void) {
858   /* Check for inquiry */
859   if ((btm_cb.btm_inq_vars.inq_active &
860        (BTM_GENERAL_INQUIRY | BTM_BLE_GENERAL_INQUIRY)) != 0) {
861     log::verbose("BTM_PM_DeviceInScanState- Inq active");
862     return true;
863   }
864 
865   return false;
866 }
867 
868 /*******************************************************************************
869  *
870  * Function         BTM_PM_ReadControllerState
871  *
872  * Description      This function is called to obtain the controller state
873  *
874  * Returns          Controller State-BTM_CONTRL_ACTIVE, BTM_CONTRL_SCAN, and
875  *                  BTM_CONTRL_IDLE
876  *
877  ******************************************************************************/
BTM_PM_ReadControllerState(void)878 tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void) {
879   if (btm_pm_device_in_active_or_sniff_mode())
880     return BTM_CONTRL_ACTIVE;
881   else if (BTM_PM_DeviceInScanState())
882     return BTM_CONTRL_SCAN;
883   else
884     return BTM_CONTRL_IDLE;
885 }
886 
887 /*******************************************************************************
888  *
889  * Function         BTM_PM_ReadSniffLinkCount
890  *
891  * Description      Return the number of BT connection in sniff mode
892  *
893  * Returns          Number of BT connection in sniff mode
894  *
895  ******************************************************************************/
BTM_PM_ReadSniffLinkCount(void)896 uint8_t BTM_PM_ReadSniffLinkCount(void) {
897   uint8_t count = 0;
898   for (auto& entry : pm_mode_db) {
899     if (entry.second.state == HCI_MODE_SNIFF) {
900       ++count;
901     }
902   }
903   return count;
904 }
905 
906 /*******************************************************************************
907  *
908  * Function         BTM_PM_ReadBleLinkCount
909  *
910  * Description      Return the number of BLE connection
911  *
912  * Returns          Number of BLE connection
913  *
914  ******************************************************************************/
BTM_PM_ReadBleLinkCount(void)915 uint8_t BTM_PM_ReadBleLinkCount(void) {
916   return btm_cb.ble_ctr_cb.link_count[HCI_ROLE_CENTRAL] +
917          btm_cb.ble_ctr_cb.link_count[HCI_ROLE_PERIPHERAL];
918 }
919 
920 /*******************************************************************************
921  *
922  * Function         BTM_PM_ReadBleScanDutyCycle
923  *
924  * Description      Returns BLE scan duty cycle which is (window * 100) /
925  *interval
926  *
927  * Returns          BLE scan duty cycle
928  *
929  ******************************************************************************/
BTM_PM_ReadBleScanDutyCycle(void)930 uint32_t BTM_PM_ReadBleScanDutyCycle(void) {
931   if (!btm_cb.ble_ctr_cb.is_ble_scan_active()) {
932     return 0;
933   }
934   uint32_t scan_window = btm_cb.ble_ctr_cb.inq_var.scan_window;
935   uint32_t scan_interval = btm_cb.ble_ctr_cb.inq_var.scan_interval;
936   log::debug("LE scan_window:{} scan interval:{}", scan_window, scan_interval);
937   return (scan_window * 100) / scan_interval;
938 }
939 
btm_pm_on_mode_change(tHCI_STATUS status,uint16_t handle,tHCI_MODE current_mode,uint16_t interval)940 void btm_pm_on_mode_change(tHCI_STATUS status, uint16_t handle,
941                            tHCI_MODE current_mode, uint16_t interval) {
942   btm_sco_chk_pend_unpark(status, handle);
943   btm_pm_proc_mode_change(status, handle, current_mode, interval);
944 }
945