1 /******************************************************************************
2  *
3  *  Copyright 2014 Google, Inc.
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 #define LOG_TAG "bt_stack_manager"
20 
21 #include "stack_manager.h"
22 
23 #include <hardware/bluetooth.h>
24 #if defined(STATIC_LIBBLUETOOTH)
25 #include <cstdlib>
26 #include <cstring>
27 #endif
28 
29 #include "btcore/include/module.h"
30 #include "btcore/include/osi_module.h"
31 #include "btif_api.h"
32 #include "btif_common.h"
33 #include "common/message_loop_thread.h"
34 #include "device/include/controller.h"
35 #include "hci/include/btsnoop.h"
36 #include "main/shim/shim.h"
37 #include "osi/include/log.h"
38 #include "osi/include/osi.h"
39 #include "osi/include/semaphore.h"
40 #include "stack/include/acl_api.h"
41 #include "stack/include/btm_client_interface.h"
42 #include "stack/include/btu.h"
43 
44 // Temp includes
45 #include "bt_utils.h"
46 #include "bta/sys/bta_sys.h"
47 #include "btif_config.h"
48 #include "btif_profile_queue.h"
49 #include "internal_include/bt_target.h"
50 #include "internal_include/bte.h"
51 #include "stack/include/gatt_api.h"
52 #include "stack/include/l2c_api.h"
53 #include "stack/include/port_api.h"
54 #include "stack/sdp/sdpint.h"
55 #if (BNEP_INCLUDED == TRUE)
56 #include "stack/include/bnep_api.h"
57 #endif
58 #include "stack/include/gap_api.h"
59 #if (PAN_INCLUDED == TRUE)
60 #include "stack/include/pan_api.h"
61 #endif
62 #include "stack/include/a2dp_api.h"
63 #include "stack/include/avrc_api.h"
64 #if (HID_HOST_INCLUDED == TRUE)
65 #include "stack/include/hidh_api.h"
66 #endif
67 #include "stack/include/smp_api.h"
68 #include "bta_ar_api.h"
69 #include "bta/sys/bta_sys_int.h"
70 #include "bta_dm_int.h"
71 #include "btif/include/btif_pan.h"
72 #include "btif/include/btif_sock.h"
73 #include "device/include/interop.h"
74 #include "internal_include/stack_config.h"
75 #include "main/shim/controller.h"
76 
77 #ifndef BT_STACK_CLEANUP_WAIT_MS
78 #define BT_STACK_CLEANUP_WAIT_MS 1000
79 #endif
80 
81 void main_thread_shut_down();
82 void main_thread_start_up();
83 void BTA_dm_on_hw_on();
84 void BTA_dm_on_hw_off();
85 
86 using bluetooth::common::MessageLoopThread;
87 
88 static MessageLoopThread management_thread("bt_stack_manager_thread");
89 
90 // If initialized, any of the bluetooth API functions can be called.
91 // (e.g. turning logging on and off, enabling/disabling the stack, etc)
92 static bool stack_is_initialized;
93 // If running, the stack is fully up and able to bluetooth.
94 static bool stack_is_running;
95 
96 static void event_init_stack(void* context);
97 static void event_start_up_stack(void* context);
98 static void event_shut_down_stack(void* context);
99 static void event_clean_up_stack(std::promise<void> promise);
100 
101 static void event_signal_stack_up(void* context);
102 static void event_signal_stack_down(void* context);
103 
104 // Unvetted includes/imports, etc which should be removed or vetted in the
105 // future
106 static future_t* hack_future;
107 // End unvetted section
108 
109 // Interface functions
110 
init_stack()111 static void init_stack() {
112   // This is a synchronous process. Post it to the thread though, so
113   // state modification only happens there. Using the thread to perform
114   // all stack operations ensures that the operations are done serially
115   // and do not overlap.
116   semaphore_t* semaphore = semaphore_new(0);
117   management_thread.DoInThread(FROM_HERE,
118                                base::Bind(event_init_stack, semaphore));
119   semaphore_wait(semaphore);
120   semaphore_free(semaphore);
121 }
122 
start_up_stack_async()123 static void start_up_stack_async() {
124   management_thread.DoInThread(FROM_HERE,
125                                base::Bind(event_start_up_stack, nullptr));
126 }
127 
shut_down_stack_async()128 static void shut_down_stack_async() {
129   management_thread.DoInThread(FROM_HERE,
130                                base::Bind(event_shut_down_stack, nullptr));
131 }
132 
clean_up_stack()133 static void clean_up_stack() {
134   // This is a synchronous process. Post it to the thread though, so
135   // state modification only happens there.
136   std::promise<void> promise;
137   auto future = promise.get_future();
138   management_thread.DoInThread(
139       FROM_HERE, base::BindOnce(event_clean_up_stack, std::move(promise)));
140 
141   auto status =
142       future.wait_for(std::chrono::milliseconds(BT_STACK_CLEANUP_WAIT_MS));
143   if (status == std::future_status::ready) {
144     management_thread.ShutDown();
145   } else {
146     LOG_ERROR("cleanup could not be completed in time, abandon it");
147   }
148 }
149 
get_stack_is_running()150 static bool get_stack_is_running() { return stack_is_running; }
151 
152 // Internal functions
153 
154 #ifdef STATIC_LIBBLUETOOTH
155 extern const module_t bt_utils_module;
156 extern const module_t bte_logmsg_module;
157 extern const module_t btif_config_module;
158 extern const module_t btsnoop_module;
159 extern const module_t bt_utils_module;
160 extern const module_t controller_module;
161 extern const module_t gd_idle_module;
162 extern const module_t gd_shim_module;
163 extern const module_t hci_module;
164 extern const module_t interop_module;
165 extern const module_t osi_module;
166 extern const module_t stack_config_module;
167 
168 struct module_lookup {
169   const char* name;
170   const module_t* module;
171 };
172 
173 const struct module_lookup module_table[] = {
174     {BTE_LOGMSG_MODULE, &bte_logmsg_module},
175     {BTIF_CONFIG_MODULE, &btif_config_module},
176     {BTSNOOP_MODULE, &btsnoop_module},
177     {BT_UTILS_MODULE, &bt_utils_module},
178     {CONTROLLER_MODULE, &controller_module},
179     {GD_IDLE_MODULE, &gd_idle_module},
180     {GD_SHIM_MODULE, &gd_shim_module},
181     {HCI_MODULE, &hci_module},
182     {INTEROP_MODULE, &interop_module},
183     {OSI_MODULE, &osi_module},
184     {STACK_CONFIG_MODULE, &stack_config_module},
185     {NULL, NULL},
186 };
187 
get_local_module(const char * name)188 inline const module_t* get_local_module(const char* name) {
189   size_t len = strlen(name);
190 
191   for (const struct module_lookup* l = module_table; l->module; l++) {
192     if (strncmp(l->name, name, len) == 0) {
193       return l->module;
194     }
195   }
196 
197   abort();
198   return nullptr;
199 }
200 #else
get_local_module(const char * name)201 inline const module_t* get_local_module(const char* name) {
202   return get_module(name);
203 }
204 #endif
205 
206 // Synchronous function to initialize the stack
event_init_stack(void * context)207 static void event_init_stack(void* context) {
208   semaphore_t* semaphore = (semaphore_t*)context;
209 
210   LOG_INFO("is initializing the stack");
211 
212   if (stack_is_initialized) {
213     LOG_INFO("found the stack already in initialized state");
214   } else {
215     module_management_start();
216 
217     module_init(get_local_module(OSI_MODULE));
218     module_init(get_local_module(BT_UTILS_MODULE));
219     if (bluetooth::shim::is_any_gd_enabled()) {
220       module_start_up(get_local_module(GD_IDLE_MODULE));
221     }
222     module_init(get_local_module(BTIF_CONFIG_MODULE));
223     btif_init_bluetooth();
224 
225     module_init(get_local_module(INTEROP_MODULE));
226     bte_main_init();
227     module_init(get_local_module(STACK_CONFIG_MODULE));
228 
229     // stack init is synchronous, so no waiting necessary here
230     stack_is_initialized = true;
231   }
232 
233   LOG_INFO("finished");
234 
235   if (semaphore) semaphore_post(semaphore);
236 }
237 
ensure_stack_is_initialized()238 static void ensure_stack_is_initialized() {
239   if (!stack_is_initialized) {
240     LOG_WARN("%s found the stack was uninitialized. Initializing now.",
241              __func__);
242     // No semaphore needed since we are calling it directly
243     event_init_stack(nullptr);
244   }
245 }
246 
247 // Synchronous function to start up the stack
event_start_up_stack(UNUSED_ATTR void * context)248 static void event_start_up_stack(UNUSED_ATTR void* context) {
249   if (stack_is_running) {
250     LOG_INFO("%s stack already brought up", __func__);
251     return;
252   }
253 
254   ensure_stack_is_initialized();
255 
256   LOG_INFO("%s is bringing up the stack", __func__);
257   future_t* local_hack_future = future_new();
258   hack_future = local_hack_future;
259 
260   if (bluetooth::shim::is_any_gd_enabled()) {
261     LOG_INFO("%s Gd shim module enabled", __func__);
262     module_shut_down(get_local_module(GD_IDLE_MODULE));
263     module_start_up(get_local_module(GD_SHIM_MODULE));
264     module_start_up(get_local_module(BTIF_CONFIG_MODULE));
265   } else {
266     module_start_up(get_local_module(BTIF_CONFIG_MODULE));
267     module_start_up(get_local_module(BTSNOOP_MODULE));
268     module_start_up(get_local_module(HCI_MODULE));
269   }
270 
271   get_btm_client_interface().lifecycle.btm_init();
272   l2c_init();
273   sdp_init();
274   gatt_init();
275   SMP_Init();
276   get_btm_client_interface().lifecycle.btm_ble_init();
277 
278   RFCOMM_Init();
279 #if (BNEP_INCLUDED == TRUE)
280   BNEP_Init();
281 #if (PAN_INCLUDED == TRUE)
282   PAN_Init();
283 #endif /* PAN */
284 #endif /* BNEP Included */
285   A2DP_Init();
286   AVRC_Init();
287   GAP_Init();
288 #if (HID_HOST_INCLUDED == TRUE)
289   HID_HostInit();
290 #endif
291 
292   bta_sys_init();
293   bta_ar_init();
294   module_init(get_local_module(BTE_LOGMSG_MODULE));
295 
296   main_thread_start_up();
297 
298   btif_init_ok();
299   BTA_dm_init();
300   bta_dm_enable(bte_dm_evt);
301 
302   bta_set_forward_hw_failures(true);
303   btm_acl_device_down();
304   if (bluetooth::shim::is_gd_controller_enabled()) {
305     CHECK(module_start_up(get_local_module(GD_CONTROLLER_MODULE)));
306   } else {
307     CHECK(module_start_up(get_local_module(CONTROLLER_MODULE)));
308   }
309   BTM_reset_complete();
310 
311   BTA_dm_on_hw_on();
312 
313   if (future_await(local_hack_future) != FUTURE_SUCCESS) {
314     LOG_ERROR("%s failed to start up the stack", __func__);
315     stack_is_running = true;  // So stack shutdown actually happens
316     event_shut_down_stack(nullptr);
317     return;
318   }
319 
320   stack_is_running = true;
321   LOG_INFO("%s finished", __func__);
322   do_in_jni_thread(FROM_HERE, base::Bind(event_signal_stack_up, nullptr));
323 }
324 
325 // Synchronous function to shut down the stack
event_shut_down_stack(UNUSED_ATTR void * context)326 static void event_shut_down_stack(UNUSED_ATTR void* context) {
327   if (!stack_is_running) {
328     LOG_INFO("%s stack is already brought down", __func__);
329     return;
330   }
331 
332   LOG_INFO("%s is bringing down the stack", __func__);
333   future_t* local_hack_future = future_new();
334   hack_future = local_hack_future;
335   stack_is_running = false;
336 
337   do_in_main_thread(FROM_HERE, base::Bind(&btm_ble_multi_adv_cleanup));
338 
339   btif_dm_on_disable();
340   btif_sock_cleanup();
341   btif_pan_cleanup();
342 
343   do_in_main_thread(FROM_HERE, base::Bind(bta_dm_disable));
344 
345   future_await(local_hack_future);
346   local_hack_future = future_new();
347   hack_future = local_hack_future;
348 
349   bta_sys_disable();
350   bta_set_forward_hw_failures(false);
351   BTA_dm_on_hw_off();
352 
353   module_shut_down(get_local_module(BTIF_CONFIG_MODULE));
354 
355   future_await(local_hack_future);
356 
357   main_thread_shut_down();
358 
359   module_clean_up(get_local_module(BTE_LOGMSG_MODULE));
360 
361   gatt_free();
362   l2c_free();
363   sdp_free();
364   get_btm_client_interface().lifecycle.btm_ble_free();
365   get_btm_client_interface().lifecycle.btm_free();
366 
367   if (bluetooth::shim::is_any_gd_enabled()) {
368     LOG_INFO("%s Gd shim module disabled", __func__);
369     module_shut_down(get_local_module(GD_SHIM_MODULE));
370     module_start_up(get_local_module(GD_IDLE_MODULE));
371   } else {
372     module_shut_down(get_local_module(HCI_MODULE));
373     module_shut_down(get_local_module(BTSNOOP_MODULE));
374   }
375 
376   module_shut_down(
377       get_local_module(CONTROLLER_MODULE));  // Doesn't do any work, just
378                                              // puts it in a restartable
379                                              // state
380 
381   hack_future = future_new();
382   do_in_jni_thread(FROM_HERE, base::Bind(event_signal_stack_down, nullptr));
383   future_await(hack_future);
384   LOG_INFO("%s finished", __func__);
385 }
386 
ensure_stack_is_not_running()387 static void ensure_stack_is_not_running() {
388   if (stack_is_running) {
389     LOG_WARN("%s found the stack was still running. Bringing it down now.",
390              __func__);
391     event_shut_down_stack(nullptr);
392   }
393 }
394 
395 // Synchronous function to clean up the stack
event_clean_up_stack(std::promise<void> promise)396 static void event_clean_up_stack(std::promise<void> promise) {
397   if (!stack_is_initialized) {
398     LOG_INFO("%s found the stack already in a clean state", __func__);
399     goto cleanup;
400   }
401 
402   ensure_stack_is_not_running();
403 
404   LOG_INFO("%s is cleaning up the stack", __func__);
405   stack_is_initialized = false;
406 
407   btif_cleanup_bluetooth();
408 
409   module_clean_up(get_local_module(STACK_CONFIG_MODULE));
410   module_clean_up(get_local_module(INTEROP_MODULE));
411 
412   module_clean_up(get_local_module(BTIF_CONFIG_MODULE));
413   module_clean_up(get_local_module(BT_UTILS_MODULE));
414   module_clean_up(get_local_module(OSI_MODULE));
415   module_shut_down(get_local_module(GD_IDLE_MODULE));
416   module_management_stop();
417   LOG_INFO("%s finished", __func__);
418 
419 cleanup:;
420   promise.set_value();
421 }
422 
event_signal_stack_up(UNUSED_ATTR void * context)423 static void event_signal_stack_up(UNUSED_ATTR void* context) {
424   // Notify BTIF connect queue that we've brought up the stack. It's
425   // now time to dispatch all the pending profile connect requests.
426   btif_queue_connect_next();
427   invoke_adapter_state_changed_cb(BT_STATE_ON);
428 }
429 
event_signal_stack_down(UNUSED_ATTR void * context)430 static void event_signal_stack_down(UNUSED_ATTR void* context) {
431   invoke_adapter_state_changed_cb(BT_STATE_OFF);
432   future_ready(stack_manager_get_hack_future(), FUTURE_SUCCESS);
433 }
434 
ensure_manager_initialized()435 static void ensure_manager_initialized() {
436   if (management_thread.IsRunning()) return;
437 
438   management_thread.StartUp();
439   if (!management_thread.IsRunning()) {
440     LOG_ERROR("%s unable to start stack management thread", __func__);
441     return;
442   }
443 }
444 
445 static const stack_manager_t interface = {init_stack, start_up_stack_async,
446                                           shut_down_stack_async, clean_up_stack,
447                                           get_stack_is_running};
448 
stack_manager_get_interface()449 const stack_manager_t* stack_manager_get_interface() {
450   ensure_manager_initialized();
451   return &interface;
452 }
453 
stack_manager_get_hack_future()454 future_t* stack_manager_get_hack_future() { return hack_future; }
455