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 <cstring>
22 #include <set>
23 #include <stdint.h>
24 #include <string>
25 
26 #if !defined PLATFORM_WINDOWS && defined __GLIBC__
27 #include <climits>
28 #include <dlfcn.h>
29 #endif
30 
31 #include "pbd/pthread_utils.h"
32 #ifdef WINE_THREAD_SUPPORT
33 #include <fst.h>
34 #endif
35 
36 #ifdef COMPILER_MSVC
37 DECLARE_DEFAULT_COMPARISONS (pthread_t) // Needed for 'DECLARE_DEFAULT_COMPARISONS'. Objects in an STL container can be
38                                         // searched and sorted. Thus, when instantiating the container, MSVC complains
39                                         // if the type of object being contained has no appropriate comparison operators
40                                         // defined (specifically, if operators '<' and '==' are undefined). This seems
41                                         // to be the case with ptw32 'pthread_t' which is a simple struct.
42 #endif
43 
44 #ifdef __APPLE__
45 #include <mach/mach_time.h>
46 #include <mach/thread_act.h>
47 #include <mach/thread_policy.h>
48 #endif
49 
50 using namespace std;
51 
52 typedef std::list<pthread_t>        ThreadMap;
53 static ThreadMap                    all_threads;
54 static pthread_mutex_t              thread_map_lock = PTHREAD_MUTEX_INITIALIZER;
55 static Glib::Threads::Private<char> thread_name (free);
56 
57 namespace PBD
58 {
59 	PBD::Signal3<void, pthread_t, std::string, uint32_t> ThreadCreatedWithRequestSize;
60 }
61 
62 using namespace PBD;
63 
64 static int
thread_creator(pthread_t * thread_id,const pthread_attr_t * attr,void * (* function)(void *),void * arg)65 thread_creator (pthread_t* thread_id, const pthread_attr_t* attr, void* (*function) (void*), void* arg)
66 {
67 #ifdef WINE_THREAD_SUPPORT
68 	return wine_pthread_create (thread_id, attr, function, arg);
69 #else
70 	return pthread_create (thread_id, attr, function, arg);
71 #endif
72 }
73 
74 void
notify_event_loops_about_thread_creation(pthread_t thread,const std::string & emitting_thread_name,int request_count)75 PBD::notify_event_loops_about_thread_creation (pthread_t thread, const std::string& emitting_thread_name, int request_count)
76 {
77 	/* notify threads that may exist in the future (they may also exist
78 	 * already, in which case they will catch the
79 	 * ThreadCreatedWithRequestSize signal)
80 	 */
81 	EventLoop::pre_register (emitting_thread_name, request_count);
82 
83 	/* notify all existing threads */
84 	ThreadCreatedWithRequestSize (thread, emitting_thread_name, request_count);
85 }
86 
87 struct ThreadStartWithName {
88 	void* (*thread_work) (void*);
89 	void*       arg;
90 	std::string name;
91 
ThreadStartWithNameThreadStartWithName92 	ThreadStartWithName (void* (*f) (void*), void* a, const std::string& s)
93 		: thread_work (f)
94 		, arg (a)
95 		, name (s)
96 	{}
97 };
98 
99 static void*
fake_thread_start(void * arg)100 fake_thread_start (void* arg)
101 {
102 	ThreadStartWithName* ts      = (ThreadStartWithName*)arg;
103 	void* (*thread_work) (void*) = ts->thread_work;
104 	void* thread_arg             = ts->arg;
105 
106 	/* name will be deleted by the default handler for GStaticPrivate, when the thread exits */
107 	pthread_set_name (ts->name.c_str ());
108 
109 	/* we don't need this object anymore */
110 	delete ts;
111 
112 	/* actually run the thread's work function */
113 	void* ret = thread_work (thread_arg);
114 
115 	/* cleanup */
116 	pthread_mutex_lock (&thread_map_lock);
117 
118 	for (ThreadMap::iterator i = all_threads.begin (); i != all_threads.end (); ++i) {
119 		if (pthread_equal ((*i), pthread_self ())) {
120 			all_threads.erase (i);
121 			break;
122 		}
123 	}
124 
125 	pthread_mutex_unlock (&thread_map_lock);
126 
127 	/* done */
128 	return ret;
129 }
130 
131 int
pthread_create_and_store(string name,pthread_t * thread,void * (* start_routine)(void *),void * arg)132 pthread_create_and_store (string name, pthread_t* thread, void* (*start_routine) (void*), void* arg)
133 {
134 	pthread_attr_t default_attr;
135 	int            ret;
136 
137 	/* set default stack size to sensible default for memlocking */
138 	pthread_attr_init (&default_attr);
139 	pthread_attr_setstacksize (&default_attr, 0x80000); // 512kB
140 
141 	ThreadStartWithName* ts = new ThreadStartWithName (start_routine, arg, name);
142 
143 	if ((ret = thread_creator (thread, &default_attr, fake_thread_start, ts)) == 0) {
144 		pthread_mutex_lock (&thread_map_lock);
145 		all_threads.push_back (*thread);
146 		pthread_mutex_unlock (&thread_map_lock);
147 	}
148 
149 	pthread_attr_destroy (&default_attr);
150 
151 	return ret;
152 }
153 
154 void
pthread_set_name(const char * str)155 pthread_set_name (const char* str)
156 {
157 	/* copy string and delete it when exiting */
158 	thread_name.set (strdup (str)); // leaks
159 
160 #if !defined PLATFORM_WINDOWS && defined _GNU_SOURCE
161 	/* set public thread name, up to 16 chars */
162 	char ptn[16];
163 	memset (ptn, 0, 16);
164 	strncpy (ptn, str, 15);
165 	pthread_setname_np (pthread_self (), ptn);
166 #endif
167 }
168 
169 const char*
pthread_name()170 pthread_name ()
171 {
172 	const char* str = thread_name.get ();
173 
174 	if (str) {
175 		return str;
176 	}
177 	return "unknown";
178 }
179 
180 void
pthread_kill_all(int signum)181 pthread_kill_all (int signum)
182 {
183 	pthread_mutex_lock (&thread_map_lock);
184 	for (ThreadMap::iterator i = all_threads.begin (); i != all_threads.end (); ++i) {
185 		if (!pthread_equal ((*i), pthread_self ())) {
186 			pthread_kill ((*i), signum);
187 		}
188 	}
189 	all_threads.clear ();
190 	pthread_mutex_unlock (&thread_map_lock);
191 }
192 
193 void
pthread_cancel_all()194 pthread_cancel_all ()
195 {
196 	pthread_mutex_lock (&thread_map_lock);
197 
198 	for (ThreadMap::iterator i = all_threads.begin (); i != all_threads.end ();) {
199 		ThreadMap::iterator nxt = i;
200 		++nxt;
201 
202 		if (!pthread_equal ((*i), pthread_self ())) {
203 			pthread_cancel ((*i));
204 		}
205 
206 		i = nxt;
207 	}
208 	all_threads.clear ();
209 	pthread_mutex_unlock (&thread_map_lock);
210 }
211 
212 void
pthread_cancel_one(pthread_t thread)213 pthread_cancel_one (pthread_t thread)
214 {
215 	pthread_mutex_lock (&thread_map_lock);
216 	for (ThreadMap::iterator i = all_threads.begin (); i != all_threads.end (); ++i) {
217 		if (pthread_equal ((*i), thread)) {
218 			all_threads.erase (i);
219 			break;
220 		}
221 	}
222 
223 	pthread_cancel (thread);
224 	pthread_mutex_unlock (&thread_map_lock);
225 }
226 
227 static size_t
pbd_stack_size()228 pbd_stack_size ()
229 {
230 	size_t rv = 0;
231 #if !defined PLATFORM_WINDOWS && defined __GLIBC__
232 
233 	size_t pt_min_stack = 16384;
234 
235 #ifdef PTHREAD_STACK_MIN
236 	pt_min_stack = PTHREAD_STACK_MIN;
237 #endif
238 
239 	void* handle = dlopen (NULL, RTLD_LAZY);
240 
241 	/* This function is internal (it has a GLIBC_PRIVATE) version, but
242 	 * available via weak symbol, or dlsym, and returns
243 	 *
244 	 * GLRO(dl_pagesize) + __static_tls_size + PTHREAD_STACK_MIN
245 	 */
246 
247 	size_t (*__pthread_get_minstack) (const pthread_attr_t* attr) =
248 	    (size_t (*) (const pthread_attr_t*))dlsym (handle, "__pthread_get_minstack");
249 
250 	if (__pthread_get_minstack != NULL) {
251 		pthread_attr_t attr;
252 		pthread_attr_init (&attr);
253 		rv = __pthread_get_minstack (&attr);
254 		assert (rv >= pt_min_stack);
255 		rv -= pt_min_stack;
256 		pthread_attr_destroy (&attr);
257 	}
258 	dlclose (handle);
259 #endif
260 	return rv;
261 }
262 
263 int
pbd_pthread_create(const size_t stacksize,pthread_t * thread,void * (* start_routine)(void *),void * arg)264 pbd_pthread_create (
265 		const size_t stacksize,
266 		pthread_t*   thread,
267 		void* (*start_routine) (void*),
268 		void* arg)
269 {
270 	int rv;
271 
272 	pthread_attr_t attr;
273 	pthread_attr_init (&attr);
274 	pthread_attr_setstacksize (&attr, stacksize + pbd_stack_size ());
275 	rv = pthread_create (thread, &attr, start_routine, arg);
276 	pthread_attr_destroy (&attr);
277 	return rv;
278 }
279 
280 int
pbd_pthread_priority(PBDThreadClass which)281 pbd_pthread_priority (PBDThreadClass which)
282 {
283 	/* fall back to use values relative to max */
284 #ifdef PLATFORM_WINDOWS
285 	switch (which) {
286 		case THREAD_MAIN:
287 			return -1;
288 		case THREAD_MIDI:
289 			return -2;
290 		default:
291 		case THREAD_PROC:
292 			return -2;
293 	}
294 #else
295 	int base = -20;
296 	const char* p = getenv ("ARDOUR_SCHED_PRI");
297 	if (p && *p) {
298 		base = atoi (p);
299 		if (base > -5 && base < 5) {
300 			base = -20;
301 		}
302 	}
303 
304 	switch (which) {
305 		case THREAD_MAIN:
306 			return base;
307 		case THREAD_MIDI:
308 			return base - 1;
309 		default:
310 		case THREAD_PROC:
311 			return base - 2;
312 	}
313 #endif
314 }
315 
316 int
pbd_absolute_rt_priority(int policy,int priority)317 pbd_absolute_rt_priority (int policy, int priority)
318 {
319 	/* POSIX requires a spread of at least 32 steps between min..max */
320 	const int p_min = sched_get_priority_min (policy); // Linux: 1
321 	const int p_max = sched_get_priority_max (policy); // Linux: 99
322 
323 	if (priority == 0) {
324 		assert (0);
325 		priority = (p_min + p_max) / 2;
326 	} else if (priority > 0) {
327 		/* value relative to minium */
328 		priority += p_min - 1;
329 	} else {
330 		/* value relative maximum */
331 		priority += p_max + 1;
332 	}
333 
334 	if (priority > p_max) {
335 		priority = p_max;
336 	}
337 	if (priority < p_min) {
338 		priority = p_min;
339 	}
340 	return priority;
341 }
342 
343 int
pbd_realtime_pthread_create(const int policy,int priority,const size_t stacksize,pthread_t * thread,void * (* start_routine)(void *),void * arg)344 pbd_realtime_pthread_create (
345 		const int policy, int priority, const size_t stacksize,
346 		pthread_t* thread,
347 		void* (*start_routine) (void*),
348 		void* arg)
349 {
350 	int rv;
351 
352 	pthread_attr_t     attr;
353 	struct sched_param parm;
354 
355 	parm.sched_priority = pbd_absolute_rt_priority (policy, priority);
356 
357 	pthread_attr_init (&attr);
358 	pthread_attr_setschedpolicy (&attr, policy);
359 	pthread_attr_setschedparam (&attr, &parm);
360 	pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
361 	pthread_attr_setinheritsched (&attr, PTHREAD_EXPLICIT_SCHED);
362 	pthread_attr_setstacksize (&attr, stacksize + pbd_stack_size ());
363 	rv = pthread_create (thread, &attr, start_routine, arg);
364 	pthread_attr_destroy (&attr);
365 	return rv;
366 }
367 
368 int
pbd_set_thread_priority(pthread_t thread,const int policy,int priority)369 pbd_set_thread_priority (pthread_t thread, const int policy, int priority)
370 {
371 	struct sched_param param;
372 	memset (&param, 0, sizeof (param));
373 	param.sched_priority = pbd_absolute_rt_priority (policy, priority);
374 
375 	return pthread_setschedparam (thread, SCHED_FIFO, &param);
376 }
377 
378 bool
pbd_mach_set_realtime_policy(pthread_t thread_id,double period_ns,bool main)379 pbd_mach_set_realtime_policy (pthread_t thread_id, double period_ns, bool main)
380 {
381 #ifdef __APPLE__
382 	/* https://opensource.apple.com/source/xnu/xnu-4570.61.1/osfmk/mach/thread_policy.h.auto.html
383 	 * https://opensource.apple.com/source/xnu/xnu-4570.61.1/:sposfmk/kern/sched.h.auto.html
384 	 */
385 	kern_return_t res;
386 
387 	/* Ask for fixed priority */
388 	thread_extended_policy_data_t tep;
389 	tep.timeshare = false;
390 
391 	res = thread_policy_set (pthread_mach_thread_np (thread_id),
392 	                         THREAD_EXTENDED_POLICY,
393 	                         (thread_policy_t)&tep,
394 	                         THREAD_EXTENDED_POLICY_COUNT);
395 #ifndef NDEBUG
396 	printf ("Mach Thread(%p) set timeshare: %d OK: %d\n", thread_id, tep.timeshare, res == KERN_SUCCESS);
397 #endif
398 
399 	/* relative value of the computation compared to the other threads in the task. */
400 	thread_precedence_policy_data_t tpp;
401 	tpp.importance = main ? 63 : 62; // MAXPRI_USER = 63
402 
403 	res = thread_policy_set (pthread_mach_thread_np (thread_id),
404 	                         THREAD_PRECEDENCE_POLICY,
405 	                         (thread_policy_t)&tpp,
406 	                         THREAD_PRECEDENCE_POLICY_COUNT);
407 #ifndef NDEBUG
408 	printf ("Mach Thread(%p) set precedence: %d OK: %d\n", thread_id, tpp.importance, res == KERN_SUCCESS);
409 #endif
410 
411 	/* Realtime constraints */
412 	double ticks_per_ns = 1.;
413 	mach_timebase_info_data_t timebase;
414 	if (KERN_SUCCESS == mach_timebase_info (&timebase)) {
415 		ticks_per_ns = timebase.denom / timebase.numer;
416 	}
417 
418 	thread_time_constraint_policy_data_t tcp;
419 #ifndef NDEBUG
420 	mach_msg_type_number_t msgt = 4;
421 	boolean_t              dflt = false;
422 	kern_return_t          rv   = thread_policy_get (pthread_mach_thread_np (thread_id),
423 	                                                 THREAD_TIME_CONSTRAINT_POLICY,
424 	                                                 (thread_policy_t)&tcp,
425 	                                                 &msgt, &dflt);
426 
427 	printf ("Mach Thread(%p) get: period=%d comp=%d constraint=%d preemt=%d OK: %d\n", thread_id, tcp.period, tcp.computation, tcp.constraint, tcp.preemptible, rv == KERN_SUCCESS);
428 #endif
429 
430 	mach_timebase_info_data_t timebase_info;
431 	mach_timebase_info (&timebase_info);
432 	const double period_clk = period_ns * (double)timebase_info.denom / (double)timebase_info.numer;
433 
434 	tcp.period      = ticks_per_ns * period_clk;
435 	tcp.computation = ticks_per_ns * period_clk * .9;
436 	tcp.constraint  = ticks_per_ns * period_clk * .95;
437 	tcp.preemptible = true;
438 
439 	res = thread_policy_set (pthread_mach_thread_np (thread_id),
440 	                         THREAD_TIME_CONSTRAINT_POLICY,
441 	                         (thread_policy_t)&tcp,
442 	                         THREAD_TIME_CONSTRAINT_POLICY_COUNT);
443 
444 #ifndef NDEBUG
445 	printf ("Mach Thread(%p) set: period=%d comp=%d constraint=%d preemt=%d OK: %d\n", thread_id, tcp.period, tcp.computation, tcp.constraint, tcp.preemptible, res == KERN_SUCCESS);
446 #endif
447 
448 	return res != KERN_SUCCESS;
449 #endif
450 	return false; // OK
451 }
452