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_osi_thread"
20 
21 #include "osi/include/thread.h"
22 
23 #include <bluetooth/log.h>
24 #include <malloc.h>
25 #include <pthread.h>
26 #include <string.h>
27 #include <sys/prctl.h>
28 #include <sys/resource.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 
32 #include <atomic>
33 #include <cerrno>
34 
35 #include "osi/include/allocator.h"
36 #include "osi/include/compat.h"
37 #include "osi/include/fixed_queue.h"
38 #include "osi/include/reactor.h"
39 #include "osi/semaphore.h"
40 
41 using namespace bluetooth;
42 
43 struct thread_t {
44   std::atomic_bool is_joined{false};
45   pthread_t pthread;
46   pid_t tid;
47   char name[THREAD_NAME_MAX + 1];
48   reactor_t* reactor;
49   fixed_queue_t* work_queue;
50 };
51 
52 struct start_arg {
53   thread_t* thread;
54   semaphore_t* start_sem;
55   int error;
56 };
57 
58 typedef struct {
59   thread_fn func;
60   void* context;
61 } work_item_t;
62 
63 static void* run_thread(void* start_arg);
64 static void work_queue_read_cb(void* context);
65 
66 static const size_t DEFAULT_WORK_QUEUE_CAPACITY = 128;
67 
thread_new_sized(const char * name,size_t work_queue_capacity)68 thread_t* thread_new_sized(const char* name, size_t work_queue_capacity) {
69   log::assert_that(name != NULL, "assert failed: name != NULL");
70   log::assert_that(work_queue_capacity != 0, "assert failed: work_queue_capacity != 0");
71 
72   thread_t* ret = static_cast<thread_t*>(osi_calloc(sizeof(thread_t)));
73 
74   ret->reactor = reactor_new();
75   if (!ret->reactor) {
76     goto error;
77   }
78 
79   ret->work_queue = fixed_queue_new(work_queue_capacity);
80   if (!ret->work_queue) {
81     goto error;
82   }
83 
84   // Start is on the stack, but we use a semaphore, so it's safe
85   struct start_arg start;
86   start.start_sem = semaphore_new(0);
87   if (!start.start_sem) {
88     goto error;
89   }
90 
91   strncpy(ret->name, name, THREAD_NAME_MAX);
92   start.thread = ret;
93   start.error = 0;
94   pthread_create(&ret->pthread, NULL, run_thread, &start);
95   semaphore_wait(start.start_sem);
96   semaphore_free(start.start_sem);
97 
98   if (start.error) {
99     goto error;
100   }
101 
102   return ret;
103 
104 error:;
105   if (ret) {
106     fixed_queue_free(ret->work_queue, osi_free);
107     reactor_free(ret->reactor);
108   }
109   osi_free(ret);
110   return NULL;
111 }
112 
thread_new(const char * name)113 thread_t* thread_new(const char* name) {
114   return thread_new_sized(name, DEFAULT_WORK_QUEUE_CAPACITY);
115 }
116 
thread_free(thread_t * thread)117 void thread_free(thread_t* thread) {
118   if (!thread) {
119     return;
120   }
121 
122   thread_stop(thread);
123   thread_join(thread);
124 
125   fixed_queue_free(thread->work_queue, osi_free);
126   reactor_free(thread->reactor);
127   osi_free(thread);
128 }
129 
thread_join(thread_t * thread)130 void thread_join(thread_t* thread) {
131   log::assert_that(thread != NULL, "assert failed: thread != NULL");
132 
133   if (!std::atomic_exchange(&thread->is_joined, true)) {
134     pthread_join(thread->pthread, NULL);
135   }
136 }
137 
thread_post(thread_t * thread,thread_fn func,void * context)138 bool thread_post(thread_t* thread, thread_fn func, void* context) {
139   log::assert_that(thread != NULL, "assert failed: thread != NULL");
140   log::assert_that(func != NULL, "assert failed: func != NULL");
141 
142   // TODO(sharvil): if the current thread == |thread| and we've run out
143   // of queue space, we should abort this operation, otherwise we'll
144   // deadlock.
145 
146   // Queue item is freed either when the queue itself is destroyed
147   // or when the item is removed from the queue for dispatch.
148   work_item_t* item = (work_item_t*)osi_malloc(sizeof(work_item_t));
149   item->func = func;
150   item->context = context;
151   fixed_queue_enqueue(thread->work_queue, item);
152   return true;
153 }
154 
thread_stop(thread_t * thread)155 void thread_stop(thread_t* thread) {
156   log::assert_that(thread != NULL, "assert failed: thread != NULL");
157   reactor_stop(thread->reactor);
158 }
159 
thread_set_priority(thread_t * thread,int priority)160 bool thread_set_priority(thread_t* thread, int priority) {
161   if (!thread) {
162     return false;
163   }
164 
165   const int rc = setpriority(PRIO_PROCESS, thread->tid, priority);
166   if (rc < 0) {
167     log::error("unable to set thread priority {} for tid {}, error {}", priority, thread->tid, rc);
168     return false;
169   }
170 
171   return true;
172 }
173 
thread_set_rt_priority(thread_t * thread,int priority)174 bool thread_set_rt_priority(thread_t* thread, int priority) {
175   if (!thread) {
176     return false;
177   }
178 
179   struct sched_param rt_params;
180   rt_params.sched_priority = priority;
181 
182   const int rc = sched_setscheduler(thread->tid, SCHED_FIFO, &rt_params);
183   if (rc != 0) {
184     log::error("unable to set SCHED_FIFO priority {} for tid {}, error {}", priority, thread->tid,
185                strerror(errno));
186     return false;
187   }
188 
189   return true;
190 }
191 
thread_is_self(const thread_t * thread)192 bool thread_is_self(const thread_t* thread) {
193   log::assert_that(thread != NULL, "assert failed: thread != NULL");
194   return !!pthread_equal(pthread_self(), thread->pthread);
195 }
196 
thread_get_reactor(const thread_t * thread)197 reactor_t* thread_get_reactor(const thread_t* thread) {
198   log::assert_that(thread != NULL, "assert failed: thread != NULL");
199   return thread->reactor;
200 }
201 
thread_name(const thread_t * thread)202 const char* thread_name(const thread_t* thread) {
203   log::assert_that(thread != NULL, "assert failed: thread != NULL");
204   return thread->name;
205 }
206 
run_thread(void * start_arg)207 static void* run_thread(void* start_arg) {
208   log::assert_that(start_arg != NULL, "assert failed: start_arg != NULL");
209 
210   struct start_arg* start = static_cast<struct start_arg*>(start_arg);
211   thread_t* thread = start->thread;
212 
213   log::assert_that(thread != NULL, "assert failed: thread != NULL");
214 
215   if (prctl(PR_SET_NAME, (unsigned long)thread->name) == -1) {
216     log::error("unable to set thread name: {}", strerror(errno));
217     start->error = errno;
218     semaphore_post(start->start_sem);
219     return NULL;
220   }
221   thread->tid = gettid();
222 
223   log::info("thread id {}, thread name {} started", thread->tid, thread->name);
224 
225   semaphore_post(start->start_sem);
226 
227   int fd = fixed_queue_get_dequeue_fd(thread->work_queue);
228   void* context = thread->work_queue;
229 
230   reactor_object_t* work_queue_object =
231           reactor_register(thread->reactor, fd, context, work_queue_read_cb, NULL);
232   log::assert_that(work_queue_object != nullptr, "assert failed: work_queue_object != nullptr");
233 
234   reactor_start(thread->reactor);
235   reactor_unregister(work_queue_object);
236 
237   // Make sure we dispatch all queued work items before exiting the thread.
238   // This allows a caller to safely tear down by enqueuing a teardown
239   // work item and then joining the thread.
240   size_t count = 0;
241   work_item_t* item = static_cast<work_item_t*>(fixed_queue_try_dequeue(thread->work_queue));
242   while (item && count <= fixed_queue_capacity(thread->work_queue)) {
243     item->func(item->context);
244     osi_free(item);
245     item = static_cast<work_item_t*>(fixed_queue_try_dequeue(thread->work_queue));
246     ++count;
247   }
248 
249   if (count > fixed_queue_capacity(thread->work_queue)) {
250     log::info("growing event queue on shutdown.");
251   }
252 
253   log::warn("thread id {}, thread name {} exited", thread->tid, thread->name);
254   return NULL;
255 }
256 
work_queue_read_cb(void * context)257 static void work_queue_read_cb(void* context) {
258   log::assert_that(context != NULL, "assert failed: context != NULL");
259 
260   fixed_queue_t* queue = (fixed_queue_t*)context;
261   work_item_t* item = static_cast<work_item_t*>(fixed_queue_dequeue(queue));
262   item->func(item->context);
263   osi_free(item);
264 }
265