fix thinko when testing for internal seek with negative distance
[ardour.git] / libs / pbd / pthread_utils.cc
1 /*
2  * Copyright (C) 2002-2015 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2007-2009 David Robillard <d@drobilla.net>
4  * Copyright (C) 2015-2018 Robin Gareus <robin@gareus.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include <set>
22 #include <string>
23 #include <cstring>
24 #include <stdint.h>
25
26 #include "pbd/pthread_utils.h"
27 #ifdef WINE_THREAD_SUPPORT
28 #include <fst.h>
29 #endif
30
31 #ifdef COMPILER_MSVC
32 DECLARE_DEFAULT_COMPARISONS(pthread_t)  // Needed for 'DECLARE_DEFAULT_COMPARISONS'. Objects in an STL container can be
33                                         // searched and sorted. Thus, when instantiating the container, MSVC complains
34                                         // if the type of object being contained has no appropriate comparison operators
35                                         // defined (specifically, if operators '<' and '==' are undefined). This seems
36                                         // to be the case with ptw32 'pthread_t' which is a simple struct.
37 #endif
38
39 using namespace std;
40
41 typedef std::list<pthread_t> ThreadMap;
42 static ThreadMap all_threads;
43 static pthread_mutex_t thread_map_lock = PTHREAD_MUTEX_INITIALIZER;
44 static Glib::Threads::Private<char> thread_name (free);
45
46 namespace PBD {
47         PBD::Signal3<void,pthread_t,std::string,uint32_t> ThreadCreatedWithRequestSize;
48 }
49
50 using namespace PBD;
51
52 static int thread_creator (pthread_t* thread_id, const pthread_attr_t* attr, void *(*function)(void*), void* arg)
53 {
54 #ifdef WINE_THREAD_SUPPORT
55        return wine_pthread_create (thread_id, attr, function, arg);
56 #else
57        return pthread_create (thread_id, attr, function, arg);
58 #endif
59 }
60
61
62 void
63 PBD::notify_event_loops_about_thread_creation (pthread_t thread, const std::string& emitting_thread_name, int request_count)
64 {
65         /* notify threads that may exist in the future (they may also exist
66          * already, in which case they will catch the
67          * ThreadCreatedWithRequestSize signal)
68          */
69         EventLoop::pre_register (emitting_thread_name, request_count);
70
71         /* notify all existing threads */
72         ThreadCreatedWithRequestSize (thread, emitting_thread_name, request_count);
73 }
74
75 struct ThreadStartWithName {
76     void* (*thread_work)(void*);
77     void* arg;
78     std::string name;
79
80     ThreadStartWithName (void* (*f)(void*), void* a, const std::string& s)
81             : thread_work (f), arg (a), name (s) {}
82 };
83
84 static void*
85 fake_thread_start (void* arg)
86 {
87         ThreadStartWithName* ts = (ThreadStartWithName*) arg;
88         void* (*thread_work)(void*) = ts->thread_work;
89         void* thread_arg = ts->arg;
90
91         /* name will be deleted by the default handler for GStaticPrivate, when the thread exits */
92
93         pthread_set_name (ts->name.c_str());
94
95         /* we don't need this object anymore */
96
97         delete ts;
98
99         /* actually run the thread's work function */
100
101         void* ret = thread_work (thread_arg);
102
103         /* cleanup */
104
105         pthread_mutex_lock (&thread_map_lock);
106
107         for (ThreadMap::iterator i = all_threads.begin(); i != all_threads.end(); ++i) {
108                 if (pthread_equal ((*i), pthread_self())) {
109                         all_threads.erase (i);
110                         break;
111                 }
112         }
113
114         pthread_mutex_unlock (&thread_map_lock);
115
116         /* done */
117
118         return ret;
119 }
120
121 int
122 pthread_create_and_store (string name, pthread_t  *thread, void * (*start_routine)(void *), void * arg)
123 {
124         pthread_attr_t default_attr;
125         int ret;
126
127         // set default stack size to sensible default for memlocking
128         pthread_attr_init(&default_attr);
129         pthread_attr_setstacksize(&default_attr, 500000);
130
131         ThreadStartWithName* ts = new ThreadStartWithName (start_routine, arg, name);
132
133         if ((ret = thread_creator (thread, &default_attr, fake_thread_start, ts)) == 0) {
134                 pthread_mutex_lock (&thread_map_lock);
135                 all_threads.push_back (*thread);
136                 pthread_mutex_unlock (&thread_map_lock);
137         }
138
139         pthread_attr_destroy(&default_attr);
140
141         return ret;
142 }
143
144 void
145 pthread_set_name (const char *str)
146 {
147         /* copy string and delete it when exiting */
148
149         thread_name.set (strdup (str)); // leaks
150 }
151
152 const char *
153 pthread_name ()
154 {
155         const char* str = thread_name.get ();
156
157         if (str) {
158                 return str;
159         }
160         return "unknown";
161 }
162
163 void
164 pthread_kill_all (int signum)
165 {
166         pthread_mutex_lock (&thread_map_lock);
167         for (ThreadMap::iterator i = all_threads.begin(); i != all_threads.end(); ++i) {
168                 if (!pthread_equal ((*i), pthread_self())) {
169                         pthread_kill ((*i), signum);
170                 }
171         }
172         all_threads.clear();
173         pthread_mutex_unlock (&thread_map_lock);
174 }
175
176 void
177 pthread_cancel_all ()
178 {
179         pthread_mutex_lock (&thread_map_lock);
180
181         for (ThreadMap::iterator i = all_threads.begin(); i != all_threads.end(); ) {
182
183                 ThreadMap::iterator nxt = i;
184                 ++nxt;
185
186                 if (!pthread_equal ((*i), pthread_self())) {
187                         pthread_cancel ((*i));
188                 }
189
190                 i = nxt;
191         }
192         all_threads.clear();
193         pthread_mutex_unlock (&thread_map_lock);
194 }
195
196 void
197 pthread_cancel_one (pthread_t thread)
198 {
199         pthread_mutex_lock (&thread_map_lock);
200         for (ThreadMap::iterator i = all_threads.begin(); i != all_threads.end(); ++i) {
201                 if (pthread_equal ((*i), thread)) {
202                         all_threads.erase (i);
203                         break;
204                 }
205         }
206
207         pthread_cancel (thread);
208         pthread_mutex_unlock (&thread_map_lock);
209 }
210
211 int
212 pbd_absolute_rt_priority (int policy, int priority)
213 {
214         /* POSIX requires a spread of at least 32 steps between min..max */
215         const int p_min = sched_get_priority_min (policy); // Linux: 1
216         const int p_max = sched_get_priority_max (policy); // Linux: 99
217
218         if (priority == 0) {
219                 /* use default. XXX this should be relative to audio (JACK) thread,
220                  * internal backends use -20 (Audio), -21 (MIDI), -22 (compuation)
221                  */
222                 priority = 7; // BaseUI backwards compat.
223         }
224
225         if (priority > 0) {
226                 priority += p_min;
227         } else {
228                 priority += p_max;
229         }
230         if (priority > p_max) priority = p_max;
231         if (priority < p_min) priority = p_min;
232         return priority;
233 }
234
235
236
237 int
238 pbd_realtime_pthread_create (
239                 const int policy, int priority, const size_t stacksize,
240                 pthread_t *thread,
241                 void *(*start_routine) (void *),
242                 void *arg)
243 {
244         int rv;
245
246         pthread_attr_t attr;
247         struct sched_param parm;
248
249         parm.sched_priority = pbd_absolute_rt_priority (policy, priority);
250
251         pthread_attr_init (&attr);
252         pthread_attr_setschedpolicy (&attr, policy);
253         pthread_attr_setschedparam (&attr, &parm);
254         pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
255         pthread_attr_setinheritsched (&attr, PTHREAD_EXPLICIT_SCHED);
256         pthread_attr_setstacksize (&attr, stacksize);
257         rv = pthread_create (thread, &attr, start_routine, arg);
258         pthread_attr_destroy (&attr);
259         return rv;
260 }
261 int
262 pbd_set_thread_priority (pthread_t thread, const int policy, int priority)
263 {
264         struct sched_param param;
265         memset (&param, 0, sizeof (param));
266         param.sched_priority = pbd_absolute_rt_priority (policy, priority);
267
268         return pthread_setschedparam (thread, SCHED_FIFO, &param);
269 }
270
271 bool
272 pbd_mach_set_realtime_policy (pthread_t thread_id, double period_ns)
273 {
274 #ifdef _APPLE_
275         thread_time_constraint_policy_data_t policy;
276 #ifndef NDEBUG
277         mach_msg_type_number_t msgt = 4;
278         boolean_t dflt = false;
279         kern_return_t rv = thread_policy_get (pthread_mach_thread_np (_main_thread),
280                         THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t) &policy,
281                         &msgt, &dflt);
282         printf ("Mach Thread(%p) %d %d %d %d DFLT %d OK: %d\n", _main_thread, policy.period, policy.computation, policy.constraint, policy.preemptible, dflt, rv == KERN_SUCCESS);
283 #endif
284
285         mach_timebase_info_data_t timebase_info;
286         mach_timebase_info(&timebase_info);
287         const double period_clk = period_ns * (double)timebase_info.denom / (double)timebase_info.numer;
288
289         policy.period = period_clk;
290         policy.computation = period_clk * .9;
291         policy.constraint = period_clk * .95;
292         policy.preemptible = true;
293         kern_return_t res = thread_policy_set (pthread_mach_thread_np (thread_id),
294                         THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t) &policy,
295                         THREAD_TIME_CONSTRAINT_POLICY_COUNT);
296
297 #ifndef NDEBUG
298         printf ("Mach Thread(%p) %d %d %d %d OK: %d\n", thread_id, policy.period, policy.computation, policy.constraint, policy.preemptible, res == KERN_SUCCESS);
299 #endif
300         return res != KERN_SUCCESS;
301 #endif
302         return false; // OK
303 }