1/******************************************************************************
2 *
3 *  Copyright (C) 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_core_module"
20
21#include <assert.h>
22#include <dlfcn.h>
23#include <pthread.h>
24#include <string.h>
25
26#include "btcore/include/module.h"
27#include "osi/include/allocator.h"
28#include "osi/include/hash_functions.h"
29#include "osi/include/hash_map.h"
30#include "osi/include/log.h"
31#include "osi/include/osi.h"
32
33typedef enum {
34  MODULE_STATE_NONE = 0,
35  MODULE_STATE_INITIALIZED = 1,
36  MODULE_STATE_STARTED = 2
37} module_state_t;
38
39static const size_t number_of_metadata_buckets = 42;
40static hash_map_t *metadata;
41// Include this lock for now for correctness, while the startup sequence is being refactored
42static pthread_mutex_t metadata_lock;
43
44static bool call_lifecycle_function(module_lifecycle_fn function);
45static module_state_t get_module_state(const module_t *module);
46static void set_module_state(const module_t *module, module_state_t state);
47
48void module_management_start(void) {
49  metadata = hash_map_new(
50    number_of_metadata_buckets,
51    hash_function_pointer,
52    NULL,
53    osi_free,
54    NULL
55  );
56
57  pthread_mutex_init(&metadata_lock, NULL);
58}
59
60void module_management_stop(void) {
61  if (!metadata)
62    return;
63
64  hash_map_free(metadata);
65  metadata = NULL;
66
67  pthread_mutex_destroy(&metadata_lock);
68}
69
70const module_t *get_module(const char *name) {
71  module_t* module = (module_t *)dlsym(RTLD_DEFAULT, name);
72  assert(module);
73  return module;
74}
75
76bool module_init(const module_t *module) {
77  assert(metadata != NULL);
78  assert(module != NULL);
79  assert(get_module_state(module) == MODULE_STATE_NONE);
80
81  LOG_INFO(LOG_TAG, "%s Initializing module \"%s\"", __func__, module->name);
82  if (!call_lifecycle_function(module->init)) {
83    LOG_ERROR(LOG_TAG, "%s Failed to initialize module \"%s\"",
84              __func__, module->name);
85    return false;
86  }
87  LOG_INFO(LOG_TAG, "%s Initialized module \"%s\"", __func__, module->name);
88
89  set_module_state(module, MODULE_STATE_INITIALIZED);
90  return true;
91}
92
93bool module_start_up(const module_t *module) {
94  assert(metadata != NULL);
95  assert(module != NULL);
96  // TODO(zachoverflow): remove module->init check once automagic order/call is in place.
97  // This hack is here so modules which don't require init don't have to have useless calls
98  // as we're converting the startup sequence.
99  assert(get_module_state(module) == MODULE_STATE_INITIALIZED || module->init == NULL);
100
101  LOG_INFO(LOG_TAG, "%s Starting module \"%s\"", __func__, module->name);
102  if (!call_lifecycle_function(module->start_up)) {
103    LOG_ERROR(LOG_TAG, "%s Failed to start up module \"%s\"",
104              __func__, module->name);
105    return false;
106  }
107  LOG_INFO(LOG_TAG, "%s Started module \"%s\"", __func__, module->name);
108
109  set_module_state(module, MODULE_STATE_STARTED);
110  return true;
111}
112
113void module_shut_down(const module_t *module) {
114  assert(metadata != NULL);
115  assert(module != NULL);
116  module_state_t state = get_module_state(module);
117  assert(state <= MODULE_STATE_STARTED);
118
119  // Only something to do if the module was actually started
120  if (state < MODULE_STATE_STARTED)
121    return;
122
123  LOG_INFO(LOG_TAG, "%s Shutting down module \"%s\"", __func__, module->name);
124  if (!call_lifecycle_function(module->shut_down)) {
125    LOG_ERROR(LOG_TAG, "%s Failed to shutdown module \"%s\". Continuing anyway.",
126              __func__, module->name);
127  }
128  LOG_INFO(LOG_TAG, "%s Shutdown of module \"%s\" completed",
129           __func__, module->name);
130
131  set_module_state(module, MODULE_STATE_INITIALIZED);
132}
133
134void module_clean_up(const module_t *module) {
135  assert(metadata != NULL);
136  assert(module != NULL);
137  module_state_t state = get_module_state(module);
138  assert(state <= MODULE_STATE_INITIALIZED);
139
140  // Only something to do if the module was actually initialized
141  if (state < MODULE_STATE_INITIALIZED)
142    return;
143
144  LOG_INFO(LOG_TAG, "%s Cleaning up module \"%s\"", __func__, module->name);
145  if (!call_lifecycle_function(module->clean_up)) {
146    LOG_ERROR(LOG_TAG, "%s Failed to cleanup module \"%s\". Continuing anyway.",
147              __func__, module->name);
148  }
149  LOG_INFO(LOG_TAG, "%s Cleanup of module \"%s\" completed",
150           __func__, module->name);
151
152  set_module_state(module, MODULE_STATE_NONE);
153}
154
155static bool call_lifecycle_function(module_lifecycle_fn function) {
156  // A NULL lifecycle function means it isn't needed, so assume success
157  if (!function)
158    return true;
159
160  future_t *future = function();
161
162  // A NULL future means synchronous success
163  if (!future)
164    return true;
165
166  // Otherwise fall back to the future
167  return future_await(future);
168}
169
170static module_state_t get_module_state(const module_t *module) {
171  pthread_mutex_lock(&metadata_lock);
172  module_state_t *state_ptr = hash_map_get(metadata, module);
173  pthread_mutex_unlock(&metadata_lock);
174
175  return state_ptr ? *state_ptr : MODULE_STATE_NONE;
176}
177
178static void set_module_state(const module_t *module, module_state_t state) {
179  pthread_mutex_lock(&metadata_lock);
180
181  module_state_t *state_ptr = hash_map_get(metadata, module);
182  if (!state_ptr) {
183    state_ptr = osi_malloc(sizeof(module_state_t));
184    hash_map_set(metadata, module, state_ptr);
185  }
186
187  pthread_mutex_unlock(&metadata_lock);
188
189  *state_ptr = state;
190}
191
192// TODO(zachoverflow): remove when everything modulized
193// Temporary callback-wrapper-related code
194
195typedef struct {
196  const module_t *module;
197  thread_t *lifecycle_thread;
198  thread_t *callback_thread; // we don't own this thread
199  thread_fn callback;
200  bool success;
201} callbacked_wrapper_t;
202
203static void run_wrapped_start_up(void *context);
204static void post_result_to_callback(void *context);
205
206void module_start_up_callbacked_wrapper(
207    const module_t *module,
208    thread_t *callback_thread,
209    thread_fn callback) {
210  callbacked_wrapper_t *wrapper = osi_calloc(sizeof(callbacked_wrapper_t));
211
212  wrapper->module = module;
213  wrapper->lifecycle_thread = thread_new("module_wrapper");
214  wrapper->callback_thread = callback_thread;
215  wrapper->callback = callback;
216
217  // Run the actual module start up
218  thread_post(wrapper->lifecycle_thread, run_wrapped_start_up, wrapper);
219}
220
221static void run_wrapped_start_up(void *context) {
222  assert(context);
223
224  callbacked_wrapper_t *wrapper = context;
225  wrapper->success = module_start_up(wrapper->module);
226
227  // Post the result back to the callback
228  thread_post(wrapper->callback_thread, post_result_to_callback, wrapper);
229}
230
231static void post_result_to_callback(void *context) {
232  assert(context);
233
234  callbacked_wrapper_t *wrapper = context;
235
236  // Save the values we need for callback
237  void *result = wrapper->success ? FUTURE_SUCCESS : FUTURE_FAIL;
238  thread_fn callback = wrapper->callback;
239
240  // Clean up the resources we used
241  thread_free(wrapper->lifecycle_thread);
242  osi_free(wrapper);
243
244  callback(result);
245}
246