1 /*
2  * Copyright (c) 2018-2023 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <pthread.h>
8 #include <semaphore.h>
9 
10 #include <zephyr/sys/util.h>
11 #include <zephyr/ztest.h>
12 
13 #define DETACH_THR_ID 2
14 
15 #define N_THR_E 3
16 #define N_THR_T 4
17 #define BOUNCES 64
18 #define ONE_SECOND 1
19 
20 /* Macros to test invalid states */
21 #define PTHREAD_CANCEL_INVALID -1
22 #define SCHED_INVALID -1
23 #define PRIO_INVALID -1
24 #define PTHREAD_INVALID -1
25 
26 static void *thread_top_exec(void *p1);
27 static void *thread_top_term(void *p1);
28 
29 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
30 static pthread_cond_t cvar0 = PTHREAD_COND_INITIALIZER;
31 static pthread_cond_t cvar1 = PTHREAD_COND_INITIALIZER;
32 static pthread_barrier_t barrier;
33 
34 static sem_t main_sem;
35 
36 static int bounce_failed;
37 static int bounce_done[N_THR_E];
38 
39 static int curr_bounce_thread;
40 
41 static int barrier_failed;
42 static int barrier_done[N_THR_E];
43 static int barrier_return[N_THR_E];
44 
45 /* First phase bounces execution between two threads using a condition
46  * variable, continuously testing that no other thread is mucking with
47  * the protected state.  This ends with all threads going back to
48  * sleep on the condition variable and being woken by main() for the
49  * second phase.
50  *
51  * Second phase simply lines up all the threads on a barrier, verifies
52  * that none run until the last one enters, and that all run after the
53  * exit.
54  *
55  * Test success is signaled to main() using a traditional semaphore.
56  */
57 
thread_top_exec(void * p1)58 static void *thread_top_exec(void *p1)
59 {
60 	int i, j, id = (int) POINTER_TO_INT(p1);
61 	int policy;
62 	struct sched_param schedparam;
63 
64 	pthread_getschedparam(pthread_self(), &policy, &schedparam);
65 	printk("Thread %d starting with scheduling policy %d & priority %d\n",
66 		 id, policy, schedparam.sched_priority);
67 	/* Try a double-lock here to exercise the failing case of
68 	 * trylock.  We don't support RECURSIVE locks, so this is
69 	 * guaranteed to fail.
70 	 */
71 	pthread_mutex_lock(&lock);
72 
73 	if (!pthread_mutex_trylock(&lock)) {
74 		printk("pthread_mutex_trylock inexplicably succeeded\n");
75 		bounce_failed = 1;
76 	}
77 
78 	pthread_mutex_unlock(&lock);
79 
80 	for (i = 0; i < BOUNCES; i++) {
81 
82 		pthread_mutex_lock(&lock);
83 
84 		/* Wait for the current owner to signal us, unless we
85 		 * are the very first thread, in which case we need to
86 		 * wait a bit to be sure the other threads get
87 		 * scheduled and wait on cvar0.
88 		 */
89 		if (!(id == 0 && i == 0)) {
90 			zassert_equal(0, pthread_cond_wait(&cvar0, &lock), "");
91 		} else {
92 			pthread_mutex_unlock(&lock);
93 			usleep(USEC_PER_MSEC * 500U);
94 			pthread_mutex_lock(&lock);
95 		}
96 
97 		/* Claim ownership, then try really hard to give someone
98 		 * else a shot at hitting this if they are racing.
99 		 */
100 		curr_bounce_thread = id;
101 		for (j = 0; j < 1000; j++) {
102 			if (curr_bounce_thread != id) {
103 				printk("Racing bounce threads\n");
104 				bounce_failed = 1;
105 				sem_post(&main_sem);
106 				pthread_mutex_unlock(&lock);
107 				return NULL;
108 			}
109 			sched_yield();
110 		}
111 
112 		/* Next one's turn, go back to the top and wait.  */
113 		pthread_cond_signal(&cvar0);
114 		pthread_mutex_unlock(&lock);
115 	}
116 
117 	/* Signal we are complete to main(), then let it wake us up.  Note
118 	 * that we are using the same mutex with both cvar0 and cvar1,
119 	 * which is non-standard but kosher per POSIX (and it works fine
120 	 * in our implementation
121 	 */
122 	pthread_mutex_lock(&lock);
123 	bounce_done[id] = 1;
124 	sem_post(&main_sem);
125 	pthread_cond_wait(&cvar1, &lock);
126 	pthread_mutex_unlock(&lock);
127 
128 	/* Now just wait on the barrier.  Make sure no one else finished
129 	 * before we wait on it, then signal that we're done
130 	 */
131 	for (i = 0; i < N_THR_E; i++) {
132 		if (barrier_done[i]) {
133 			printk("Barrier exited early\n");
134 			barrier_failed = 1;
135 			sem_post(&main_sem);
136 		}
137 	}
138 	barrier_return[id] = pthread_barrier_wait(&barrier);
139 	barrier_done[id] = 1;
140 	sem_post(&main_sem);
141 	pthread_exit(p1);
142 
143 	return NULL;
144 }
145 
bounce_test_done(void)146 static int bounce_test_done(void)
147 {
148 	int i;
149 
150 	if (bounce_failed) {
151 		return 1;
152 	}
153 
154 	for (i = 0; i < N_THR_E; i++) {
155 		if (!bounce_done[i]) {
156 			return 0;
157 		}
158 	}
159 
160 	return 1;
161 }
162 
barrier_test_done(void)163 static int barrier_test_done(void)
164 {
165 	int i;
166 
167 	if (barrier_failed) {
168 		return 1;
169 	}
170 
171 	for (i = 0; i < N_THR_E; i++) {
172 		if (!barrier_done[i]) {
173 			return 0;
174 		}
175 	}
176 
177 	return 1;
178 }
179 
thread_top_term(void * p1)180 static void *thread_top_term(void *p1)
181 {
182 	pthread_t self;
183 	int policy, ret;
184 	int id = POINTER_TO_INT(p1);
185 	struct sched_param param, getschedparam;
186 
187 	param.sched_priority = N_THR_T - id;
188 
189 	self = pthread_self();
190 
191 	/* Change priority of thread */
192 	zassert_false(pthread_setschedparam(self, SCHED_RR, &param),
193 		      "Unable to set thread priority!");
194 
195 	zassert_false(pthread_getschedparam(self, &policy, &getschedparam),
196 			"Unable to get thread priority!");
197 
198 	printk("Thread %d starting with a priority of %d\n",
199 			id,
200 			getschedparam.sched_priority);
201 
202 	if (id % 2) {
203 		ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
204 		zassert_false(ret, "Unable to set cancel state!");
205 	}
206 
207 	if (id >= DETACH_THR_ID) {
208 		zassert_ok(pthread_detach(self), "failed to set detach state");
209 		zassert_equal(pthread_detach(self), EINVAL, "re-detached thread!");
210 	}
211 
212 	printk("Cancelling thread %d\n", id);
213 	pthread_cancel(self);
214 	printk("Thread %d could not be cancelled\n", id);
215 	sleep(ONE_SECOND);
216 	pthread_exit(p1);
217 	return NULL;
218 }
219 
220 /* Test the internal priority conversion functions */
221 int zephyr_to_posix_priority(int z_prio, int *policy);
222 int posix_to_zephyr_priority(int priority, int policy);
ZTEST(pthread,test_pthread_priority_conversion)223 ZTEST(pthread, test_pthread_priority_conversion)
224 {
225 	/*
226 	 *    ZEPHYR [-CONFIG_NUM_COOP_PRIORITIES, -1]
227 	 *                       TO
228 	 * POSIX(FIFO) [0, CONFIG_NUM_COOP_PRIORITIES - 1]
229 	 */
230 	for (int z_prio = -CONFIG_NUM_COOP_PRIORITIES, prio = CONFIG_NUM_COOP_PRIORITIES - 1,
231 		 p_prio, policy;
232 	     z_prio <= -1; z_prio++, prio--) {
233 		p_prio = zephyr_to_posix_priority(z_prio, &policy);
234 		zassert_equal(policy, SCHED_FIFO);
235 		zassert_equal(p_prio, prio, "%d %d\n", p_prio, prio);
236 		zassert_equal(z_prio, posix_to_zephyr_priority(p_prio, SCHED_FIFO));
237 	}
238 
239 	/*
240 	 *  ZEPHYR [0, CONFIG_NUM_PREEMPT_PRIORITIES - 1]
241 	 *                      TO
242 	 * POSIX(RR) [0, CONFIG_NUM_PREEMPT_PRIORITIES - 1]
243 	 */
244 	for (int z_prio = 0, prio = CONFIG_NUM_PREEMPT_PRIORITIES - 1, p_prio, policy;
245 	     z_prio < CONFIG_NUM_PREEMPT_PRIORITIES; z_prio++, prio--) {
246 		p_prio = zephyr_to_posix_priority(z_prio, &policy);
247 		zassert_equal(policy, SCHED_RR);
248 		zassert_equal(p_prio, prio, "%d %d\n", p_prio, prio);
249 		zassert_equal(z_prio, posix_to_zephyr_priority(p_prio, SCHED_RR));
250 	}
251 }
252 
ZTEST(pthread,test_pthread_execution)253 ZTEST(pthread, test_pthread_execution)
254 {
255 	int i, ret;
256 	pthread_t newthread[N_THR_E];
257 	void *retval;
258 	int serial_threads = 0;
259 	static const char thr_name[] = "thread name";
260 	char thr_name_buf[CONFIG_THREAD_MAX_NAME_LEN];
261 
262 	/*
263 	 * initialize barriers the standard way after deprecating
264 	 * PTHREAD_BARRIER_DEFINE().
265 	 */
266 	zassert_ok(pthread_barrier_init(&barrier, NULL, N_THR_E));
267 
268 	sem_init(&main_sem, 0, 1);
269 
270 	/* TESTPOINT: Try getting name of NULL thread (aka uninitialized
271 	 * thread var).
272 	 */
273 	ret = pthread_getname_np(PTHREAD_INVALID, thr_name_buf, sizeof(thr_name_buf));
274 	zassert_equal(ret, ESRCH, "uninitialized getname!");
275 
276 	for (i = 0; i < N_THR_E; i++) {
277 		ret = pthread_create(&newthread[i], NULL, thread_top_exec, INT_TO_POINTER(i));
278 	}
279 
280 	/* TESTPOINT: Try setting name of NULL thread (aka uninitialized
281 	 * thread var).
282 	 */
283 	ret = pthread_setname_np(PTHREAD_INVALID, thr_name);
284 	zassert_equal(ret, ESRCH, "uninitialized setname!");
285 
286 	/* TESTPOINT: Try getting thread name with no buffer */
287 	ret = pthread_getname_np(newthread[0], NULL, sizeof(thr_name_buf));
288 	zassert_equal(ret, EINVAL, "uninitialized getname!");
289 
290 	/* TESTPOINT: Try setting thread name with no buffer */
291 	ret = pthread_setname_np(newthread[0], NULL);
292 	zassert_equal(ret, EINVAL, "uninitialized setname!");
293 
294 	/* TESTPOINT: Try setting thread name */
295 	ret = pthread_setname_np(newthread[0], thr_name);
296 	zassert_false(ret, "Set thread name failed!");
297 
298 	/* TESTPOINT: Try getting thread name */
299 	ret = pthread_getname_np(newthread[0], thr_name_buf,
300 				 sizeof(thr_name_buf));
301 	zassert_false(ret, "Get thread name failed!");
302 
303 	/* TESTPOINT: Thread names match */
304 	ret = strncmp(thr_name, thr_name_buf, MIN(strlen(thr_name), strlen(thr_name_buf)));
305 	zassert_false(ret, "Thread names don't match!");
306 
307 	while (!bounce_test_done()) {
308 		sem_wait(&main_sem);
309 	}
310 
311 	/* TESTPOINT: Check if bounce test passes */
312 	zassert_false(bounce_failed, "Bounce test failed");
313 
314 	printk("Bounce test OK\n");
315 
316 	/* Wake up the worker threads */
317 	pthread_mutex_lock(&lock);
318 	pthread_cond_broadcast(&cvar1);
319 	pthread_mutex_unlock(&lock);
320 
321 	while (!barrier_test_done()) {
322 		sem_wait(&main_sem);
323 	}
324 
325 	/* TESTPOINT: Check if barrier test passes */
326 	zassert_false(barrier_failed, "Barrier test failed");
327 
328 	for (i = 0; i < N_THR_E; i++) {
329 		pthread_join(newthread[i], &retval);
330 	}
331 
332 	for (i = 0; i < N_THR_E; i++) {
333 		if (barrier_return[i] == PTHREAD_BARRIER_SERIAL_THREAD) {
334 			++serial_threads;
335 		}
336 	}
337 
338 	/* TESTPOINT: Check only one PTHREAD_BARRIER_SERIAL_THREAD returned. */
339 	zassert_true(serial_threads == 1, "Bungled barrier return value(s)");
340 
341 	printk("Barrier test OK\n");
342 }
343 
ZTEST(pthread,test_pthread_termination)344 ZTEST(pthread, test_pthread_termination)
345 {
346 	int32_t i, ret;
347 	pthread_t newthread[N_THR_T] = {0};
348 	void *retval;
349 
350 	/* Creating 4 threads */
351 	for (i = 0; i < N_THR_T; i++) {
352 		zassert_ok(pthread_create(&newthread[i], NULL, thread_top_term, INT_TO_POINTER(i)));
353 	}
354 
355 	/* TESTPOINT: Try setting invalid cancel state to current thread */
356 	ret = pthread_setcancelstate(PTHREAD_CANCEL_INVALID, NULL);
357 	zassert_equal(ret, EINVAL, "invalid cancel state set!");
358 
359 	for (i = 0; i < N_THR_T; i++) {
360 		if (i < DETACH_THR_ID) {
361 			zassert_ok(pthread_join(newthread[i], &retval));
362 		}
363 	}
364 
365 	/* TESTPOINT: Test for deadlock */
366 	ret = pthread_join(pthread_self(), &retval);
367 	zassert_equal(ret, EDEADLK, "thread joined with self inexplicably!");
368 
369 	/* TESTPOINT: Try canceling a terminated thread */
370 	ret = pthread_cancel(newthread[0]);
371 	zassert_equal(ret, ESRCH, "cancelled a terminated thread!");
372 }
373 
create_thread1(void * p1)374 static void *create_thread1(void *p1)
375 {
376 	/* do nothing */
377 	return NULL;
378 }
379 
ZTEST(pthread,test_pthread_descriptor_leak)380 ZTEST(pthread, test_pthread_descriptor_leak)
381 {
382 	pthread_t pthread1;
383 
384 	/* If we are leaking descriptors, then this loop will never complete */
385 	for (size_t i = 0; i < CONFIG_POSIX_THREAD_THREADS_MAX * 2; ++i) {
386 		zassert_ok(pthread_create(&pthread1, NULL, create_thread1, NULL),
387 			   "unable to create thread %zu", i);
388 		zassert_ok(pthread_join(pthread1, NULL), "unable to join thread %zu", i);
389 	}
390 }
391 
ZTEST(pthread,test_sched_getparam)392 ZTEST(pthread, test_sched_getparam)
393 {
394 	struct sched_param param;
395 	int rc = sched_getparam(0, &param);
396 	int err = errno;
397 
398 	zassert_true((rc == -1 && err == ENOSYS));
399 }
400 
ZTEST(pthread,test_sched_getscheduler)401 ZTEST(pthread, test_sched_getscheduler)
402 {
403 	int rc = sched_getscheduler(0);
404 	int err = errno;
405 
406 	zassert_true((rc == -1 && err == ENOSYS));
407 }
ZTEST(pthread,test_sched_setparam)408 ZTEST(pthread, test_sched_setparam)
409 {
410 	struct sched_param param = {
411 		.sched_priority = 2,
412 	};
413 	int rc = sched_setparam(0, &param);
414 	int err = errno;
415 
416 	zassert_true((rc == -1 && err == ENOSYS));
417 }
418 
ZTEST(pthread,test_sched_setscheduler)419 ZTEST(pthread, test_sched_setscheduler)
420 {
421 	struct sched_param param = {
422 		.sched_priority = 2,
423 	};
424 	int policy = 0;
425 	int rc = sched_setscheduler(0, policy, &param);
426 	int err = errno;
427 
428 	zassert_true((rc == -1 && err == ENOSYS));
429 }
430 
ZTEST(pthread,test_sched_rr_get_interval)431 ZTEST(pthread, test_sched_rr_get_interval)
432 {
433 	struct timespec interval = {
434 		.tv_sec = 0,
435 		.tv_nsec = 0,
436 	};
437 	int rc = sched_rr_get_interval(0, &interval);
438 	int err = errno;
439 
440 	zassert_true((rc == -1 && err == ENOSYS));
441 }
442 
ZTEST(pthread,test_pthread_equal)443 ZTEST(pthread, test_pthread_equal)
444 {
445 	zassert_true(pthread_equal(pthread_self(), pthread_self()));
446 	zassert_false(pthread_equal(pthread_self(), (pthread_t)4242));
447 }
448 
ZTEST(pthread,test_pthread_set_get_concurrency)449 ZTEST(pthread, test_pthread_set_get_concurrency)
450 {
451 	/* EINVAL if the value specified by new_level is negative */
452 	zassert_equal(EINVAL, pthread_setconcurrency(-42));
453 
454 	/*
455 	 * Note: the special value 0 indicates the implementation will
456 	 * maintain the concurrency level at its own discretion.
457 	 *
458 	 * pthread_getconcurrency() should return a value of 0 on init.
459 	 */
460 	zassert_equal(0, pthread_getconcurrency());
461 
462 	for (int i = 0; i <= CONFIG_MP_MAX_NUM_CPUS; ++i) {
463 		zassert_ok(pthread_setconcurrency(i));
464 		/* verify parameter is saved */
465 		zassert_equal(i, pthread_getconcurrency());
466 	}
467 
468 	/* EAGAIN if the a system resource to be exceeded */
469 	zassert_equal(EAGAIN, pthread_setconcurrency(CONFIG_MP_MAX_NUM_CPUS + 1));
470 }
471 
cleanup_handler(void * arg)472 static void cleanup_handler(void *arg)
473 {
474 	bool *boolp = (bool *)arg;
475 
476 	*boolp = true;
477 }
478 
test_pthread_cleanup_entry(void * arg)479 static void *test_pthread_cleanup_entry(void *arg)
480 {
481 	bool executed[2] = {0};
482 
483 	pthread_cleanup_push(cleanup_handler, &executed[0]);
484 	pthread_cleanup_push(cleanup_handler, &executed[1]);
485 	pthread_cleanup_pop(false);
486 	pthread_cleanup_pop(true);
487 
488 	zassert_true(executed[0]);
489 	zassert_false(executed[1]);
490 
491 	return NULL;
492 }
493 
ZTEST(pthread,test_pthread_cleanup)494 ZTEST(pthread, test_pthread_cleanup)
495 {
496 	pthread_t th;
497 
498 	zassert_ok(pthread_create(&th, NULL, test_pthread_cleanup_entry, NULL));
499 	zassert_ok(pthread_join(th, NULL));
500 }
501 
502 static bool testcancel_ignored;
503 static bool testcancel_failed;
504 
test_pthread_cancel_fn(void * arg)505 static void *test_pthread_cancel_fn(void *arg)
506 {
507 	zassert_ok(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL));
508 
509 	testcancel_ignored = false;
510 
511 	/* this should be ignored */
512 	pthread_testcancel();
513 
514 	testcancel_ignored = true;
515 
516 	/* this will mark it pending */
517 	zassert_ok(pthread_cancel(pthread_self()));
518 
519 	/* enable the thread to be cancelled */
520 	zassert_ok(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL));
521 
522 	testcancel_failed = false;
523 
524 	/* this should terminate the thread */
525 	pthread_testcancel();
526 
527 	testcancel_failed = true;
528 
529 	return NULL;
530 }
531 
ZTEST(pthread,test_pthread_testcancel)532 ZTEST(pthread, test_pthread_testcancel)
533 {
534 	pthread_t th;
535 
536 	zassert_ok(pthread_create(&th, NULL, test_pthread_cancel_fn, NULL));
537 	zassert_ok(pthread_join(th, NULL));
538 	zassert_true(testcancel_ignored);
539 	zassert_false(testcancel_failed);
540 }
541 
test_pthread_setschedprio_fn(void * arg)542 static void *test_pthread_setschedprio_fn(void *arg)
543 {
544 	int policy;
545 	int prio = 0;
546 	struct sched_param param;
547 	pthread_t self = pthread_self();
548 
549 	zassert_equal(pthread_setschedprio(self, PRIO_INVALID), EINVAL, "EINVAL was expected");
550 	zassert_equal(pthread_setschedprio(PTHREAD_INVALID, prio), ESRCH, "ESRCH was expected");
551 
552 	zassert_ok(pthread_setschedprio(self, prio));
553 	param.sched_priority = ~prio;
554 	zassert_ok(pthread_getschedparam(self, &policy, &param));
555 	zassert_equal(param.sched_priority, prio, "Priority unchanged");
556 
557 	return NULL;
558 }
559 
ZTEST(pthread,test_pthread_setschedprio)560 ZTEST(pthread, test_pthread_setschedprio)
561 {
562 	pthread_t th;
563 
564 	zassert_ok(pthread_create(&th, NULL, test_pthread_setschedprio_fn, NULL));
565 	zassert_ok(pthread_join(th, NULL));
566 }
567 
before(void * arg)568 static void before(void *arg)
569 {
570 	ARG_UNUSED(arg);
571 
572 	if (!IS_ENABLED(CONFIG_DYNAMIC_THREAD)) {
573 		/* skip redundant testing if there is no thread pool / heap allocation */
574 		ztest_test_skip();
575 	}
576 }
577 
578 ZTEST_SUITE(pthread, NULL, NULL, before, NULL, NULL);
579