1 /*
2  * Copyright 2019 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 #pragma once
18 
19 #include <functional>
20 #include <mutex>
21 
22 #include "module.h"
23 #include "os/handler.h"
24 #include "os/thread.h"
25 #include "stack_manager.h"
26 
27 // The shim layer implementation on the Gd stack side.
28 namespace bluetooth {
29 namespace shim {
30 
31 class Acl;
32 class Btm;
33 
34 // GD shim stack, having modes corresponding to legacy stack
35 class Stack {
36 public:
37   static Stack* GetInstance();
38 
39   Stack();
40   Stack(const Stack&) = delete;
41   Stack& operator=(const Stack&) = delete;
42 
43   ~Stack() = default;
44 
45   // Running mode, everything is up
46   void StartEverything();
47 
48   void Stop();
49   bool IsRunning();
50   bool IsDumpsysModuleStarted() const;
51 
52   StackManager* GetStackManager();
53   const StackManager* GetStackManager() const;
54 
55   Acl* GetAcl();
56 
57   os::Handler* GetHandler();
58 
59   bool LockForDumpsys(std::function<void()> dumpsys_callback);
60 
61   // Start the list of modules with the given stack manager thread
62   void StartModuleStack(const ModuleList* modules, const os::Thread* thread);
63 
64   // Run the callable object on the module instance
65   template <typename T>
CallOnModule(std::function<void (T * mod)> run)66   bool CallOnModule(std::function<void(T* mod)> run) {
67     std::lock_guard<std::recursive_mutex> lock(mutex_);
68     if (is_running_) {
69       run(stack_manager_.GetInstance<T>());
70     }
71     return is_running_;
72   }
73 
NumModules()74   size_t NumModules() const { return num_modules_; }
75 
76 private:
77   struct impl;
78   std::shared_ptr<impl> pimpl_;
79 
80   mutable std::recursive_mutex mutex_;
81   StackManager stack_manager_;
82   bool is_running_ = false;
83   os::Thread* stack_thread_ = nullptr;
84   os::Handler* stack_handler_ = nullptr;
85   size_t num_modules_{0};
86   void Start(ModuleList* modules);
87 };
88 
89 }  // namespace shim
90 }  // namespace bluetooth
91