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