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