2 * Copyright (c) 2009 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
31 #include <sys/kdebug.h>
39 #include <sys/sysctl.h>
43 #include <spawn_private.h>
44 #include <sys/spawn_internal.h>
45 #include <mach-o/dyld.h>
47 #include <mach/mach_time.h>
48 #include <mach/mach.h>
49 #include <mach/task.h>
50 #include <mach/semaphore.h>
52 #include <pthread/qos_private.h>
54 #include <sys/resource.h>
56 #include <stdatomic.h>
59 #include <TargetConditionals.h>
61 typedef enum wake_type
{ WAKE_BROADCAST_ONESEM
, WAKE_BROADCAST_PERTHREAD
, WAKE_CHAIN
, WAKE_HOP
} wake_type_t
;
62 typedef enum my_policy_type
{ MY_POLICY_REALTIME
, MY_POLICY_TIMESHARE
, MY_POLICY_FIXEDPRI
} my_policy_type_t
;
64 #define mach_assert_zero(error) do { if ((error) != 0) { fprintf(stderr, "[FAIL] error %d (%s) ", (error), mach_error_string(error)); assert(error == 0); } } while (0)
65 #define mach_assert_zero_t(tid, error) do { if ((error) != 0) { fprintf(stderr, "[FAIL] Thread %d error %d (%s) ", (tid), (error), mach_error_string(error)); assert(error == 0); } } while (0)
66 #define assert_zero_t(tid, error) do { if ((error) != 0) { fprintf(stderr, "[FAIL] Thread %d error %d ", (tid), (error)); assert(error == 0); } } while (0)
68 #define CONSTRAINT_NANOS (20000000ll) /* 20 ms */
69 #define COMPUTATION_NANOS (10000000ll) /* 10 ms */
70 #define LL_CONSTRAINT_NANOS ( 2000000ll) /* 2 ms */
71 #define LL_COMPUTATION_NANOS ( 1000000ll) /* 1 ms */
72 #define RT_CHURN_COMP_NANOS ( 1000000ll) /* 1 ms */
73 #define TRACEWORTHY_NANOS (10000000ll) /* 10 ms */
74 #define TRACEWORTHY_NANOS_TEST ( 2000000ll) /* 2 ms */
77 #define debug_log(args ...) printf(args)
79 #define debug_log(args ...) do { } while(0)
83 static void* worker_thread(void *arg
);
85 static int thread_setup(uint32_t my_id
);
86 static my_policy_type_t
parse_thread_policy(const char *str
);
87 static void selfexec_with_apptype(int argc
, char *argv
[]);
88 static void parse_args(int argc
, char *argv
[]);
90 static __attribute__((aligned(128))) _Atomic
uint32_t g_done_threads
;
91 static __attribute__((aligned(128))) _Atomic boolean_t g_churn_stop
= FALSE
;
92 static __attribute__((aligned(128))) _Atomic
uint64_t g_churn_stopped_at
= 0;
94 /* Global variables (general) */
95 static uint32_t g_numcpus
;
96 static uint32_t g_nphysicalcpu
;
97 static uint32_t g_nlogicalcpu
;
98 static uint32_t g_numthreads
;
99 static wake_type_t g_waketype
;
100 static policy_t g_policy
;
101 static uint32_t g_iterations
;
102 static struct mach_timebase_info g_mti
;
103 static semaphore_t g_main_sem
;
104 static uint64_t *g_thread_endtimes_abs
;
105 static boolean_t g_verbose
= FALSE
;
106 static boolean_t g_do_affinity
= FALSE
;
107 static uint64_t g_starttime_abs
;
108 static uint32_t g_iteration_sleeptime_us
= 0;
109 static uint32_t g_priority
= 0;
110 static uint32_t g_churn_pri
= 0;
111 static uint32_t g_churn_count
= 0;
112 static uint32_t g_rt_churn_count
= 0;
114 static pthread_t
* g_churn_threads
= NULL
;
115 static pthread_t
* g_rt_churn_threads
= NULL
;
117 /* should we skip test if run on non-intel */
118 static boolean_t g_run_on_intel_only
= FALSE
;
120 /* Threshold for dropping a 'bad run' tracepoint */
121 static uint64_t g_traceworthy_latency_ns
= TRACEWORTHY_NANOS
;
123 /* Have we re-execed to set apptype? */
124 static boolean_t g_seen_apptype
= FALSE
;
126 /* usleep in betweeen iterations */
127 static boolean_t g_do_sleep
= TRUE
;
129 /* Every thread spins until all threads have checked in */
130 static boolean_t g_do_all_spin
= FALSE
;
132 /* Every thread backgrounds temporarily before parking */
133 static boolean_t g_drop_priority
= FALSE
;
135 /* Use low-latency (sub 4ms deadline) realtime threads */
136 static boolean_t g_rt_ll
= FALSE
;
138 /* Test whether realtime threads are scheduled on the separate CPUs */
139 static boolean_t g_test_rt
= FALSE
;
141 static boolean_t g_rt_churn
= FALSE
;
143 /* On SMT machines, test whether realtime threads are scheduled on the correct CPUs */
144 static boolean_t g_test_rt_smt
= FALSE
;
146 /* Test whether realtime threads are successfully avoiding CPU 0 on Intel */
147 static boolean_t g_test_rt_avoid0
= FALSE
;
149 /* Print a histgram showing how many threads ran on each CPU */
150 static boolean_t g_histogram
= FALSE
;
152 /* One randomly chosen thread holds up the train for a certain duration. */
153 static boolean_t g_do_one_long_spin
= FALSE
;
154 static uint32_t g_one_long_spin_id
= 0;
155 static uint64_t g_one_long_spin_length_abs
= 0;
156 static uint64_t g_one_long_spin_length_ns
= 0;
158 /* Each thread spins for a certain duration after waking up before blocking again. */
159 static boolean_t g_do_each_spin
= FALSE
;
160 static uint64_t g_each_spin_duration_abs
= 0;
161 static uint64_t g_each_spin_duration_ns
= 0;
163 /* Global variables (broadcast) */
164 static semaphore_t g_broadcastsem
;
165 static semaphore_t g_leadersem
;
166 static semaphore_t g_readysem
;
167 static semaphore_t g_donesem
;
168 static semaphore_t g_rt_churn_sem
;
169 static semaphore_t g_rt_churn_start_sem
;
171 /* Global variables (chain) */
172 static semaphore_t
*g_semarr
;
175 __attribute__((aligned(128))) uint32_t current
;
179 static histogram_t
*g_cpu_histogram
;
180 static _Atomic
uint64_t *g_cpu_map
;
183 abs_to_nanos(uint64_t abstime
)
185 return (uint64_t)(abstime
* (((double)g_mti
.numer
) / ((double)g_mti
.denom
)));
189 nanos_to_abs(uint64_t ns
)
191 return (uint64_t)(ns
* (((double)g_mti
.denom
) / ((double)g_mti
.numer
)));
197 #if defined(__arm__) || defined(__arm64__)
198 asm volatile ("yield");
199 #elif defined(__x86_64__) || defined(__i386__)
200 asm volatile ("pause");
202 #error Unrecognized architecture
207 churn_thread(__unused
void *arg
)
209 uint64_t spin_count
= 0;
212 * As a safety measure to avoid wedging, we will bail on the spin if
213 * it's been more than 1s after the most recent run start
216 while (g_churn_stop
== FALSE
&&
217 mach_absolute_time() < (g_starttime_abs
+ NSEC_PER_SEC
)) {
222 /* This is totally racy, but only here to detect if anyone stops early */
223 atomic_fetch_add_explicit(&g_churn_stopped_at
, spin_count
, memory_order_relaxed
);
229 create_churn_threads()
231 if (g_churn_count
== 0) {
232 g_churn_count
= g_numcpus
- 1;
237 struct sched_param param
= { .sched_priority
= (int)g_churn_pri
};
240 /* Array for churn threads */
241 g_churn_threads
= (pthread_t
*) valloc(sizeof(pthread_t
) * g_churn_count
);
242 assert(g_churn_threads
);
244 if ((err
= pthread_attr_init(&attr
))) {
245 errc(EX_OSERR
, err
, "pthread_attr_init");
248 if ((err
= pthread_attr_setschedparam(&attr
, ¶m
))) {
249 errc(EX_OSERR
, err
, "pthread_attr_setschedparam");
252 if ((err
= pthread_attr_setschedpolicy(&attr
, SCHED_RR
))) {
253 errc(EX_OSERR
, err
, "pthread_attr_setschedpolicy");
256 for (uint32_t i
= 0; i
< g_churn_count
; i
++) {
257 pthread_t new_thread
;
259 if ((err
= pthread_create(&new_thread
, &attr
, churn_thread
, NULL
))) {
260 errc(EX_OSERR
, err
, "pthread_create");
262 g_churn_threads
[i
] = new_thread
;
265 if ((err
= pthread_attr_destroy(&attr
))) {
266 errc(EX_OSERR
, err
, "pthread_attr_destroy");
271 join_churn_threads(void)
273 if (atomic_load_explicit(&g_churn_stopped_at
, memory_order_seq_cst
) != 0) {
274 printf("Warning: Some of the churn threads may have stopped early: %lld\n",
278 atomic_store_explicit(&g_churn_stop
, TRUE
, memory_order_seq_cst
);
280 /* Rejoin churn threads */
281 for (uint32_t i
= 0; i
< g_churn_count
; i
++) {
282 errno_t err
= pthread_join(g_churn_threads
[i
], NULL
);
284 errc(EX_OSERR
, err
, "pthread_join %d", i
);
293 rt_churn_thread_setup(void)
296 thread_time_constraint_policy_data_t pol
;
298 /* Hard-coded realtime parameters (similar to what Digi uses) */
300 pol
.constraint
= (uint32_t) nanos_to_abs(CONSTRAINT_NANOS
* 2);
301 pol
.computation
= (uint32_t) nanos_to_abs(RT_CHURN_COMP_NANOS
* 2);
302 pol
.preemptible
= 0; /* Ignored by OS */
304 kr
= thread_policy_set(mach_thread_self(), THREAD_TIME_CONSTRAINT_POLICY
,
305 (thread_policy_t
) &pol
, THREAD_TIME_CONSTRAINT_POLICY_COUNT
);
306 mach_assert_zero_t(0, kr
);
312 rt_churn_thread(__unused
void *arg
)
314 rt_churn_thread_setup();
316 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
317 kern_return_t kr
= semaphore_wait_signal(g_rt_churn_start_sem
, g_rt_churn_sem
);
318 mach_assert_zero_t(0, kr
);
320 volatile double x
= 0.0;
321 volatile double y
= 0.0;
323 uint64_t endspin
= mach_absolute_time() + nanos_to_abs(RT_CHURN_COMP_NANOS
);
324 while (mach_absolute_time() < endspin
) {
330 kern_return_t kr
= semaphore_signal(g_rt_churn_sem
);
331 mach_assert_zero_t(0, kr
);
337 wait_for_rt_churn_threads(void)
339 for (uint32_t i
= 0; i
< g_rt_churn_count
; i
++) {
340 kern_return_t kr
= semaphore_wait(g_rt_churn_sem
);
341 mach_assert_zero_t(0, kr
);
346 start_rt_churn_threads(void)
348 for (uint32_t i
= 0; i
< g_rt_churn_count
; i
++) {
349 kern_return_t kr
= semaphore_signal(g_rt_churn_start_sem
);
350 mach_assert_zero_t(0, kr
);
355 create_rt_churn_threads(void)
357 if (g_rt_churn_count
== 0) {
358 /* Leave 1 CPU to ensure that the main thread can make progress */
359 g_rt_churn_count
= g_numcpus
- 1;
364 struct sched_param param
= { .sched_priority
= (int)g_churn_pri
};
367 /* Array for churn threads */
368 g_rt_churn_threads
= (pthread_t
*) valloc(sizeof(pthread_t
) * g_rt_churn_count
);
369 assert(g_rt_churn_threads
);
371 if ((err
= pthread_attr_init(&attr
))) {
372 errc(EX_OSERR
, err
, "pthread_attr_init");
375 if ((err
= pthread_attr_setschedparam(&attr
, ¶m
))) {
376 errc(EX_OSERR
, err
, "pthread_attr_setschedparam");
379 if ((err
= pthread_attr_setschedpolicy(&attr
, SCHED_RR
))) {
380 errc(EX_OSERR
, err
, "pthread_attr_setschedpolicy");
383 for (uint32_t i
= 0; i
< g_rt_churn_count
; i
++) {
384 pthread_t new_thread
;
386 if ((err
= pthread_create(&new_thread
, &attr
, rt_churn_thread
, NULL
))) {
387 errc(EX_OSERR
, err
, "pthread_create");
389 g_rt_churn_threads
[i
] = new_thread
;
392 if ((err
= pthread_attr_destroy(&attr
))) {
393 errc(EX_OSERR
, err
, "pthread_attr_destroy");
396 /* Wait until all threads have checked in */
397 wait_for_rt_churn_threads();
401 join_rt_churn_threads(void)
403 /* Rejoin rt churn threads */
404 for (uint32_t i
= 0; i
< g_rt_churn_count
; i
++) {
405 errno_t err
= pthread_join(g_rt_churn_threads
[i
], NULL
);
407 errc(EX_OSERR
, err
, "pthread_join %d", i
);
413 * Figure out what thread policy to use
415 static my_policy_type_t
416 parse_thread_policy(const char *str
)
418 if (strcmp(str
, "timeshare") == 0) {
419 return MY_POLICY_TIMESHARE
;
420 } else if (strcmp(str
, "realtime") == 0) {
421 return MY_POLICY_REALTIME
;
422 } else if (strcmp(str
, "fixed") == 0) {
423 return MY_POLICY_FIXEDPRI
;
425 errx(EX_USAGE
, "Invalid thread policy \"%s\"", str
);
430 * Figure out what wakeup pattern to use
433 parse_wakeup_pattern(const char *str
)
435 if (strcmp(str
, "chain") == 0) {
437 } else if (strcmp(str
, "hop") == 0) {
439 } else if (strcmp(str
, "broadcast-single-sem") == 0) {
440 return WAKE_BROADCAST_ONESEM
;
441 } else if (strcmp(str
, "broadcast-per-thread") == 0) {
442 return WAKE_BROADCAST_PERTHREAD
;
444 errx(EX_USAGE
, "Invalid wakeup pattern \"%s\"", str
);
452 thread_setup(uint32_t my_id
)
456 thread_time_constraint_policy_data_t pol
;
459 int policy
= SCHED_OTHER
;
460 if (g_policy
== MY_POLICY_FIXEDPRI
) {
464 struct sched_param param
= {.sched_priority
= (int)g_priority
};
465 if ((ret
= pthread_setschedparam(pthread_self(), policy
, ¶m
))) {
466 errc(EX_OSERR
, ret
, "pthread_setschedparam: %d", my_id
);
471 case MY_POLICY_TIMESHARE
:
473 case MY_POLICY_REALTIME
:
474 /* Hard-coded realtime parameters (similar to what Digi uses) */
477 pol
.constraint
= (uint32_t) nanos_to_abs(LL_CONSTRAINT_NANOS
);
478 pol
.computation
= (uint32_t) nanos_to_abs(LL_COMPUTATION_NANOS
);
480 pol
.constraint
= (uint32_t) nanos_to_abs(CONSTRAINT_NANOS
);
481 pol
.computation
= (uint32_t) nanos_to_abs(COMPUTATION_NANOS
);
483 pol
.preemptible
= 0; /* Ignored by OS */
485 kr
= thread_policy_set(mach_thread_self(), THREAD_TIME_CONSTRAINT_POLICY
,
486 (thread_policy_t
) &pol
, THREAD_TIME_CONSTRAINT_POLICY_COUNT
);
487 mach_assert_zero_t(my_id
, kr
);
489 case MY_POLICY_FIXEDPRI
:
490 ret
= pthread_set_fixedpriority_self();
492 errc(EX_OSERR
, ret
, "pthread_set_fixedpriority_self");
496 errx(EX_USAGE
, "invalid policy type %d", g_policy
);
500 thread_affinity_policy_data_t affinity
;
502 affinity
.affinity_tag
= my_id
% 2;
504 kr
= thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY
,
505 (thread_policy_t
)&affinity
, THREAD_AFFINITY_POLICY_COUNT
);
506 mach_assert_zero_t(my_id
, kr
);
513 * Wait for a wakeup, potentially wake up another of the "0-N" threads,
514 * and notify the main thread when done.
517 worker_thread(void *arg
)
519 uint32_t my_id
= (uint32_t)(uintptr_t)arg
;
522 volatile double x
= 0.0;
523 volatile double y
= 0.0;
525 /* Set policy and so forth */
528 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
531 * Leader thread either wakes everyone up or starts the chain going.
534 /* Give the worker threads undisturbed time to finish before waiting on them */
536 usleep(g_iteration_sleeptime_us
);
539 debug_log("%d Leader thread wait for ready\n", i
);
542 * Wait for everyone else to declare ready
543 * Is there a better way to do this that won't interfere with the rest of the chain?
544 * TODO: Invent 'semaphore wait for N signals'
547 for (uint32_t j
= 0; j
< g_numthreads
- 1; j
++) {
548 kr
= semaphore_wait(g_readysem
);
549 mach_assert_zero_t(my_id
, kr
);
552 debug_log("%d Leader thread wait\n", i
);
555 for (int cpuid
= 0; cpuid
< g_numcpus
; cpuid
++) {
556 if (g_cpu_histogram
[cpuid
].current
== 1) {
557 atomic_fetch_or_explicit(&g_cpu_map
[i
- 1], (1UL << cpuid
), memory_order_relaxed
);
558 g_cpu_histogram
[cpuid
].current
= 0;
563 /* Signal main thread and wait for start of iteration */
565 kr
= semaphore_wait_signal(g_leadersem
, g_main_sem
);
566 mach_assert_zero_t(my_id
, kr
);
568 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
570 debug_log("%d Leader thread go\n", i
);
572 assert_zero_t(my_id
, atomic_load_explicit(&g_done_threads
, memory_order_relaxed
));
574 switch (g_waketype
) {
575 case WAKE_BROADCAST_ONESEM
:
576 kr
= semaphore_signal_all(g_broadcastsem
);
577 mach_assert_zero_t(my_id
, kr
);
579 case WAKE_BROADCAST_PERTHREAD
:
580 for (uint32_t j
= 1; j
< g_numthreads
; j
++) {
581 kr
= semaphore_signal(g_semarr
[j
]);
582 mach_assert_zero_t(my_id
, kr
);
586 kr
= semaphore_signal(g_semarr
[my_id
+ 1]);
587 mach_assert_zero_t(my_id
, kr
);
590 kr
= semaphore_wait_signal(g_donesem
, g_semarr
[my_id
+ 1]);
591 mach_assert_zero_t(my_id
, kr
);
596 * Everyone else waits to be woken up,
597 * records when she wakes up, and possibly
600 switch (g_waketype
) {
601 case WAKE_BROADCAST_ONESEM
:
602 kr
= semaphore_wait_signal(g_broadcastsem
, g_readysem
);
603 mach_assert_zero_t(my_id
, kr
);
605 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
608 case WAKE_BROADCAST_PERTHREAD
:
609 kr
= semaphore_wait_signal(g_semarr
[my_id
], g_readysem
);
610 mach_assert_zero_t(my_id
, kr
);
612 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
616 kr
= semaphore_wait_signal(g_semarr
[my_id
], g_readysem
);
617 mach_assert_zero_t(my_id
, kr
);
619 /* Signal the next thread *after* recording wake time */
621 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
623 if (my_id
< (g_numthreads
- 1)) {
624 kr
= semaphore_signal(g_semarr
[my_id
+ 1]);
625 mach_assert_zero_t(my_id
, kr
);
631 kr
= semaphore_wait_signal(g_semarr
[my_id
], g_readysem
);
632 mach_assert_zero_t(my_id
, kr
);
634 /* Signal the next thread *after* recording wake time */
636 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
638 if (my_id
< (g_numthreads
- 1)) {
639 kr
= semaphore_wait_signal(g_donesem
, g_semarr
[my_id
+ 1]);
640 mach_assert_zero_t(my_id
, kr
);
642 kr
= semaphore_signal_all(g_donesem
);
643 mach_assert_zero_t(my_id
, kr
);
650 unsigned int cpuid
= _os_cpu_number();
651 assert(cpuid
< g_numcpus
);
652 debug_log("Thread %p woke up on CPU %d for iteration %d.\n", pthread_self(), cpuid
, i
);
653 g_cpu_histogram
[cpuid
].current
= 1;
654 g_cpu_histogram
[cpuid
].accum
++;
656 if (g_do_one_long_spin
&& g_one_long_spin_id
== my_id
) {
657 /* One randomly chosen thread holds up the train for a while. */
659 uint64_t endspin
= g_starttime_abs
+ g_one_long_spin_length_abs
;
660 while (mach_absolute_time() < endspin
) {
666 if (g_do_each_spin
) {
667 /* Each thread spins for a certain duration after waking up before blocking again. */
669 uint64_t endspin
= mach_absolute_time() + g_each_spin_duration_abs
;
670 while (mach_absolute_time() < endspin
) {
676 uint32_t done_threads
;
677 done_threads
= atomic_fetch_add_explicit(&g_done_threads
, 1, memory_order_relaxed
) + 1;
679 debug_log("Thread %p new value is %d, iteration %d\n", pthread_self(), done_threads
, i
);
681 if (g_drop_priority
) {
682 /* Drop priority to BG momentarily */
683 errno_t ret
= setpriority(PRIO_DARWIN_THREAD
, 0, PRIO_DARWIN_BG
);
685 errc(EX_OSERR
, ret
, "setpriority PRIO_DARWIN_BG");
690 /* Everyone spins until the last thread checks in. */
692 while (atomic_load_explicit(&g_done_threads
, memory_order_relaxed
) < g_numthreads
) {
698 if (g_drop_priority
) {
699 /* Restore normal priority */
700 errno_t ret
= setpriority(PRIO_DARWIN_THREAD
, 0, 0);
702 errc(EX_OSERR
, ret
, "setpriority 0");
706 debug_log("Thread %p done spinning, iteration %d\n", pthread_self(), i
);
710 /* Give the worker threads undisturbed time to finish before waiting on them */
712 usleep(g_iteration_sleeptime_us
);
715 /* Wait for the worker threads to finish */
716 for (uint32_t i
= 0; i
< g_numthreads
- 1; i
++) {
717 kr
= semaphore_wait(g_readysem
);
718 mach_assert_zero_t(my_id
, kr
);
721 /* Tell everyone and the main thread that the last iteration is done */
722 debug_log("%d Leader thread done\n", g_iterations
- 1);
724 for (int cpuid
= 0; cpuid
< g_numcpus
; cpuid
++) {
725 if (g_cpu_histogram
[cpuid
].current
== 1) {
726 atomic_fetch_or_explicit(&g_cpu_map
[g_iterations
- 1], (1UL << cpuid
), memory_order_relaxed
);
727 g_cpu_histogram
[cpuid
].current
= 0;
731 kr
= semaphore_signal_all(g_main_sem
);
732 mach_assert_zero_t(my_id
, kr
);
734 /* Hold up thread teardown so it doesn't affect the last iteration */
735 kr
= semaphore_wait_signal(g_main_sem
, g_readysem
);
736 mach_assert_zero_t(my_id
, kr
);
743 * Given an array of uint64_t values, compute average, max, min, and standard deviation
746 compute_stats(uint64_t *values
, uint64_t count
, float *averagep
, uint64_t *maxp
, uint64_t *minp
, float *stddevp
)
751 uint64_t _min
= UINT64_MAX
;
755 for (i
= 0; i
< count
; i
++) {
757 _max
= values
[i
] > _max
? values
[i
] : _max
;
758 _min
= values
[i
] < _min
? values
[i
] : _min
;
761 _avg
= ((float)_sum
) / ((float)count
);
764 for (i
= 0; i
< count
; i
++) {
765 _dev
+= powf((((float)values
[i
]) - _avg
), 2);
778 main(int argc
, char **argv
)
784 uint64_t *worst_latencies_ns
;
785 uint64_t *worst_latencies_from_first_ns
;
789 bool test_fail
= false;
791 for (int i
= 0; i
< argc
; i
++) {
792 if (strcmp(argv
[i
], "--switched_apptype") == 0) {
793 g_seen_apptype
= TRUE
;
797 if (!g_seen_apptype
) {
798 selfexec_with_apptype(argc
, argv
);
801 parse_args(argc
, argv
);
803 srand((unsigned int)time(NULL
));
805 mach_timebase_info(&g_mti
);
808 /* SKIP test if running on arm platform */
809 if (g_run_on_intel_only
) {
811 size_t is_arm_size
= sizeof(is_arm
);
812 ret
= sysctlbyname("hw.optional.arm64", &is_arm
, &is_arm_size
, NULL
, 0);
813 if (ret
== 0 && is_arm
) {
814 printf("Unsupported platform. Skipping test.\n");
818 #endif /* TARGET_OS_OSX */
820 size_t ncpu_size
= sizeof(g_numcpus
);
821 ret
= sysctlbyname("hw.ncpu", &g_numcpus
, &ncpu_size
, NULL
, 0);
823 err(EX_OSERR
, "Failed sysctlbyname(hw.ncpu)");
825 assert(g_numcpus
<= 64); /* g_cpu_map needs to be extended for > 64 cpus */
827 size_t physicalcpu_size
= sizeof(g_nphysicalcpu
);
828 ret
= sysctlbyname("hw.physicalcpu", &g_nphysicalcpu
, &physicalcpu_size
, NULL
, 0);
830 err(EX_OSERR
, "Failed sysctlbyname(hw.physicalcpu)");
833 size_t logicalcpu_size
= sizeof(g_nlogicalcpu
);
834 ret
= sysctlbyname("hw.logicalcpu", &g_nlogicalcpu
, &logicalcpu_size
, NULL
, 0);
836 err(EX_OSERR
, "Failed sysctlbyname(hw.logicalcpu)");
840 if (g_numthreads
== 0) {
841 g_numthreads
= g_numcpus
;
843 g_policy
= MY_POLICY_REALTIME
;
844 g_do_all_spin
= TRUE
;
846 /* Don't change g_traceworthy_latency_ns if it's explicity been set to something other than the default */
847 if (g_traceworthy_latency_ns
== TRACEWORTHY_NANOS
) {
848 g_traceworthy_latency_ns
= TRACEWORTHY_NANOS_TEST
;
850 } else if (g_test_rt_smt
) {
851 if (g_nlogicalcpu
!= 2 * g_nphysicalcpu
) {
853 printf("Attempt to run --test-rt-smt on a non-SMT device\n");
857 if (g_numthreads
== 0) {
858 g_numthreads
= g_nphysicalcpu
;
860 g_policy
= MY_POLICY_REALTIME
;
861 g_do_all_spin
= TRUE
;
863 } else if (g_test_rt_avoid0
) {
864 #if defined(__x86_64__) || defined(__i386__)
865 if (g_numthreads
== 0) {
866 g_numthreads
= g_nphysicalcpu
- 1;
868 if (g_numthreads
== 0) {
869 printf("Attempt to run --test-rt-avoid0 on a uniprocessor\n");
872 g_policy
= MY_POLICY_REALTIME
;
873 g_do_all_spin
= TRUE
;
876 printf("Attempt to run --test-rt-avoid0 on a non-Intel device\n");
879 } else if (g_numthreads
== 0) {
880 g_numthreads
= g_numcpus
;
883 if (g_do_each_spin
) {
884 g_each_spin_duration_abs
= nanos_to_abs(g_each_spin_duration_ns
);
887 /* Configure the long-spin thread to take up half of its computation */
888 if (g_do_one_long_spin
) {
889 g_one_long_spin_length_ns
= COMPUTATION_NANOS
/ 2;
890 g_one_long_spin_length_abs
= nanos_to_abs(g_one_long_spin_length_ns
);
893 /* Estimate the amount of time the cleanup phase needs to back off */
894 g_iteration_sleeptime_us
= g_numthreads
* 20;
896 uint32_t threads_per_core
= (g_numthreads
/ g_numcpus
) + 1;
897 if (g_do_each_spin
) {
898 g_iteration_sleeptime_us
+= threads_per_core
* (g_each_spin_duration_ns
/ NSEC_PER_USEC
);
900 if (g_do_one_long_spin
) {
901 g_iteration_sleeptime_us
+= g_one_long_spin_length_ns
/ NSEC_PER_USEC
;
904 /* Arrays for threads and their wakeup times */
905 threads
= (pthread_t
*) valloc(sizeof(pthread_t
) * g_numthreads
);
908 size_t endtimes_size
= sizeof(uint64_t) * g_numthreads
;
910 g_thread_endtimes_abs
= (uint64_t*) valloc(endtimes_size
);
911 assert(g_thread_endtimes_abs
);
913 /* Ensure the allocation is pre-faulted */
914 ret
= memset_s(g_thread_endtimes_abs
, endtimes_size
, 0, endtimes_size
);
916 errc(EX_OSERR
, ret
, "memset_s endtimes");
919 size_t latencies_size
= sizeof(uint64_t) * g_iterations
;
921 worst_latencies_ns
= (uint64_t*) valloc(latencies_size
);
922 assert(worst_latencies_ns
);
924 /* Ensure the allocation is pre-faulted */
925 ret
= memset_s(worst_latencies_ns
, latencies_size
, 0, latencies_size
);
927 errc(EX_OSERR
, ret
, "memset_s latencies");
930 worst_latencies_from_first_ns
= (uint64_t*) valloc(latencies_size
);
931 assert(worst_latencies_from_first_ns
);
933 /* Ensure the allocation is pre-faulted */
934 ret
= memset_s(worst_latencies_from_first_ns
, latencies_size
, 0, latencies_size
);
936 errc(EX_OSERR
, ret
, "memset_s latencies_from_first");
939 size_t histogram_size
= sizeof(histogram_t
) * g_numcpus
;
940 g_cpu_histogram
= (histogram_t
*)valloc(histogram_size
);
941 assert(g_cpu_histogram
);
942 /* Ensure the allocation is pre-faulted */
943 ret
= memset_s(g_cpu_histogram
, histogram_size
, 0, histogram_size
);
945 errc(EX_OSERR
, ret
, "memset_s g_cpu_histogram");
948 size_t map_size
= sizeof(uint64_t) * g_iterations
;
949 g_cpu_map
= (_Atomic
uint64_t *)valloc(map_size
);
951 /* Ensure the allocation is pre-faulted */
952 ret
= memset_s(g_cpu_map
, map_size
, 0, map_size
);
954 errc(EX_OSERR
, ret
, "memset_s g_cpu_map");
957 kr
= semaphore_create(mach_task_self(), &g_main_sem
, SYNC_POLICY_FIFO
, 0);
958 mach_assert_zero(kr
);
960 /* Either one big semaphore or one per thread */
961 if (g_waketype
== WAKE_CHAIN
||
962 g_waketype
== WAKE_BROADCAST_PERTHREAD
||
963 g_waketype
== WAKE_HOP
) {
964 g_semarr
= valloc(sizeof(semaphore_t
) * g_numthreads
);
967 for (uint32_t i
= 0; i
< g_numthreads
; i
++) {
968 kr
= semaphore_create(mach_task_self(), &g_semarr
[i
], SYNC_POLICY_FIFO
, 0);
969 mach_assert_zero(kr
);
972 g_leadersem
= g_semarr
[0];
974 kr
= semaphore_create(mach_task_self(), &g_broadcastsem
, SYNC_POLICY_FIFO
, 0);
975 mach_assert_zero(kr
);
976 kr
= semaphore_create(mach_task_self(), &g_leadersem
, SYNC_POLICY_FIFO
, 0);
977 mach_assert_zero(kr
);
980 if (g_waketype
== WAKE_HOP
) {
981 kr
= semaphore_create(mach_task_self(), &g_donesem
, SYNC_POLICY_FIFO
, 0);
982 mach_assert_zero(kr
);
985 kr
= semaphore_create(mach_task_self(), &g_readysem
, SYNC_POLICY_FIFO
, 0);
986 mach_assert_zero(kr
);
988 kr
= semaphore_create(mach_task_self(), &g_rt_churn_sem
, SYNC_POLICY_FIFO
, 0);
989 mach_assert_zero(kr
);
991 kr
= semaphore_create(mach_task_self(), &g_rt_churn_start_sem
, SYNC_POLICY_FIFO
, 0);
992 mach_assert_zero(kr
);
994 atomic_store_explicit(&g_done_threads
, 0, memory_order_relaxed
);
996 /* Create the threads */
997 for (uint32_t i
= 0; i
< g_numthreads
; i
++) {
998 ret
= pthread_create(&threads
[i
], NULL
, worker_thread
, (void*)(uintptr_t)i
);
1000 errc(EX_OSERR
, ret
, "pthread_create %d", i
);
1004 ret
= setpriority(PRIO_DARWIN_ROLE
, 0, PRIO_DARWIN_ROLE_UI_FOCAL
);
1006 errc(EX_OSERR
, ret
, "setpriority");
1011 g_starttime_abs
= mach_absolute_time();
1014 create_churn_threads();
1017 create_rt_churn_threads();
1020 /* Let everyone get settled */
1021 kr
= semaphore_wait(g_main_sem
);
1022 mach_assert_zero(kr
);
1024 /* Give the system a bit more time to settle */
1026 usleep(g_iteration_sleeptime_us
);
1030 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
1032 uint64_t worst_abs
= 0, best_abs
= UINT64_MAX
;
1034 if (g_do_one_long_spin
) {
1035 g_one_long_spin_id
= (uint32_t)rand() % g_numthreads
;
1039 start_rt_churn_threads();
1043 debug_log("%d Main thread reset\n", i
);
1045 atomic_store_explicit(&g_done_threads
, 0, memory_order_seq_cst
);
1047 g_starttime_abs
= mach_absolute_time();
1049 /* Fire them off and wait for worker threads to finish */
1050 kr
= semaphore_wait_signal(g_main_sem
, g_leadersem
);
1051 mach_assert_zero(kr
);
1053 debug_log("%d Main thread return\n", i
);
1055 assert(atomic_load_explicit(&g_done_threads
, memory_order_relaxed
) == g_numthreads
);
1058 wait_for_rt_churn_threads();
1062 * We report the worst latencies relative to start time
1063 * and relative to the lead worker thread.
1065 for (j
= 0; j
< g_numthreads
; j
++) {
1066 uint64_t latency_abs
;
1068 latency_abs
= g_thread_endtimes_abs
[j
] - g_starttime_abs
;
1069 worst_abs
= worst_abs
< latency_abs
? latency_abs
: worst_abs
;
1072 worst_latencies_ns
[i
] = abs_to_nanos(worst_abs
);
1075 for (j
= 1; j
< g_numthreads
; j
++) {
1076 uint64_t latency_abs
;
1078 latency_abs
= g_thread_endtimes_abs
[j
] - g_thread_endtimes_abs
[0];
1079 worst_abs
= worst_abs
< latency_abs
? latency_abs
: worst_abs
;
1080 best_abs
= best_abs
> latency_abs
? latency_abs
: best_abs
;
1083 worst_latencies_from_first_ns
[i
] = abs_to_nanos(worst_abs
);
1086 * In the event of a bad run, cut a trace point.
1088 if (worst_latencies_from_first_ns
[i
] > g_traceworthy_latency_ns
) {
1089 /* Ariadne's ad-hoc test signpost */
1090 kdebug_trace(ARIADNEDBG_CODE(0, 0), worst_latencies_from_first_ns
[i
], g_traceworthy_latency_ns
, 0, 0);
1093 printf("Worst on this round was %.2f us.\n", ((float)worst_latencies_from_first_ns
[i
]) / 1000.0);
1097 /* Give the system a bit more time to settle */
1099 usleep(g_iteration_sleeptime_us
);
1103 /* Rejoin threads */
1104 for (uint32_t i
= 0; i
< g_numthreads
; i
++) {
1105 ret
= pthread_join(threads
[i
], NULL
);
1107 errc(EX_OSERR
, ret
, "pthread_join %d", i
);
1112 join_rt_churn_threads();
1116 join_churn_threads();
1119 compute_stats(worst_latencies_ns
, g_iterations
, &avg
, &max
, &min
, &stddev
);
1120 printf("Results (from a stop):\n");
1121 printf("Max:\t\t%.2f us\n", ((float)max
) / 1000.0);
1122 printf("Min:\t\t%.2f us\n", ((float)min
) / 1000.0);
1123 printf("Avg:\t\t%.2f us\n", avg
/ 1000.0);
1124 printf("Stddev:\t\t%.2f us\n", stddev
/ 1000.0);
1128 compute_stats(worst_latencies_from_first_ns
, g_iterations
, &avg
, &max
, &min
, &stddev
);
1129 printf("Results (relative to first thread):\n");
1130 printf("Max:\t\t%.2f us\n", ((float)max
) / 1000.0);
1131 printf("Min:\t\t%.2f us\n", ((float)min
) / 1000.0);
1132 printf("Avg:\t\t%.2f us\n", avg
/ 1000.0);
1133 printf("Stddev:\t\t%.2f us\n", stddev
/ 1000.0);
1136 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
1137 printf("Iteration %d: %f us\n", i
, worst_latencies_ns
[i
] / 1000.0);
1144 for (uint32_t i
= 0; i
< g_numcpus
; i
++) {
1145 printf("%d\t%d\n", i
, g_cpu_histogram
[i
].accum
);
1149 if (g_test_rt
|| g_test_rt_smt
|| g_test_rt_avoid0
) {
1150 #define PRIMARY 0x5555555555555555ULL
1151 #define SECONDARY 0xaaaaaaaaaaaaaaaaULL
1155 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
1156 bool secondary
= false;
1158 uint64_t map
= g_cpu_map
[i
];
1159 if (g_test_rt_smt
) {
1160 /* Test for one or more threads running on secondary cores unexpectedly (WARNING) */
1161 secondary
= (map
& SECONDARY
);
1162 /* Test for threads running on both primary and secondary cpus of the same core (FAIL) */
1163 fail
= ((map
& PRIMARY
) & ((map
& SECONDARY
) >> 1));
1164 } else if (g_test_rt
) {
1165 fail
= (__builtin_popcountll(map
) != g_numthreads
) && (worst_latencies_ns
[i
] > g_traceworthy_latency_ns
);
1166 } else if (g_test_rt_avoid0
) {
1167 fail
= ((map
& 0x1) == 0x1);
1169 if (secondary
|| fail
) {
1170 printf("Iteration %d: 0x%llx%s%s\n", i
, map
,
1171 secondary
? " SECONDARY" : "",
1172 fail
? " FAIL" : "");
1178 if (test_fail
&& (g_iterations
>= 100) && (fail_count
<= g_iterations
/ 100)) {
1179 printf("99%% or better success rate\n");
1185 free(g_thread_endtimes_abs
);
1186 free(worst_latencies_ns
);
1187 free(worst_latencies_from_first_ns
);
1188 free(g_cpu_histogram
);
1195 * WARNING: This is SPI specifically intended for use by launchd to start UI
1196 * apps. We use it here for a test tool only to opt into QoS using the same
1197 * policies. Do not use this outside xnu or libxpc/launchd.
1200 selfexec_with_apptype(int argc
, char *argv
[])
1203 posix_spawnattr_t attr
;
1204 extern char **environ
;
1205 char *new_argv
[argc
+ 1 + 1 /* NULL */];
1207 char prog
[PATH_MAX
];
1208 uint32_t prog_size
= PATH_MAX
;
1210 ret
= _NSGetExecutablePath(prog
, &prog_size
);
1212 err(EX_OSERR
, "_NSGetExecutablePath");
1215 for (i
= 0; i
< argc
; i
++) {
1216 new_argv
[i
] = argv
[i
];
1219 new_argv
[i
] = "--switched_apptype";
1220 new_argv
[i
+ 1] = NULL
;
1222 ret
= posix_spawnattr_init(&attr
);
1224 errc(EX_OSERR
, ret
, "posix_spawnattr_init");
1227 ret
= posix_spawnattr_setflags(&attr
, POSIX_SPAWN_SETEXEC
);
1229 errc(EX_OSERR
, ret
, "posix_spawnattr_setflags");
1232 ret
= posix_spawnattr_setprocesstype_np(&attr
, POSIX_SPAWN_PROC_TYPE_APP_DEFAULT
);
1234 errc(EX_OSERR
, ret
, "posix_spawnattr_setprocesstype_np");
1237 ret
= posix_spawn(NULL
, prog
, NULL
, &attr
, new_argv
, environ
);
1239 errc(EX_OSERR
, ret
, "posix_spawn");
1244 * Admittedly not very attractive.
1246 static void __attribute__((noreturn
))
1249 errx(EX_USAGE
, "Usage: %s <threads> <chain | hop | broadcast-single-sem | broadcast-per-thread> "
1250 "<realtime | timeshare | fixed> <iterations>\n\t\t"
1251 "[--trace <traceworthy latency in ns>] "
1252 "[--verbose] [--spin-one] [--spin-all] [--spin-time <nanos>] [--affinity]\n\t\t"
1253 "[--no-sleep] [--drop-priority] [--churn-pri <pri>] [--churn-count <n>]\n\t\t"
1254 "[--rt-churn] [--rt-churn-count <n>] [--rt-ll] [--test-rt] [--test-rt-smt] [--test-rt-avoid0]",
1258 static struct option
* g_longopts
;
1259 static int option_index
;
1265 /* char* optarg is a magic global */
1267 uint32_t arg_val
= (uint32_t)strtoull(optarg
, &cp
, 10);
1269 if (cp
== optarg
|| *cp
) {
1270 errx(EX_USAGE
, "arg --%s requires a decimal number, found \"%s\"",
1271 g_longopts
[option_index
].name
, optarg
);
1278 parse_args(int argc
, char *argv
[])
1290 static struct option longopts
[] = {
1291 /* BEGIN IGNORE CODESTYLE */
1292 { "spin-time", required_argument
, NULL
, OPT_SPIN_TIME
},
1293 { "trace", required_argument
, NULL
, OPT_TRACE
},
1294 { "priority", required_argument
, NULL
, OPT_PRIORITY
},
1295 { "churn-pri", required_argument
, NULL
, OPT_CHURN_PRI
},
1296 { "churn-count", required_argument
, NULL
, OPT_CHURN_COUNT
},
1297 { "rt-churn-count", required_argument
, NULL
, OPT_RT_CHURN_COUNT
},
1298 { "switched_apptype", no_argument
, (int*)&g_seen_apptype
, TRUE
},
1299 { "spin-one", no_argument
, (int*)&g_do_one_long_spin
, TRUE
},
1300 { "intel-only", no_argument
, (int*)&g_run_on_intel_only
, TRUE
},
1301 { "spin-all", no_argument
, (int*)&g_do_all_spin
, TRUE
},
1302 { "affinity", no_argument
, (int*)&g_do_affinity
, TRUE
},
1303 { "no-sleep", no_argument
, (int*)&g_do_sleep
, FALSE
},
1304 { "drop-priority", no_argument
, (int*)&g_drop_priority
, TRUE
},
1305 { "test-rt", no_argument
, (int*)&g_test_rt
, TRUE
},
1306 { "test-rt-smt", no_argument
, (int*)&g_test_rt_smt
, TRUE
},
1307 { "test-rt-avoid0", no_argument
, (int*)&g_test_rt_avoid0
, TRUE
},
1308 { "rt-churn", no_argument
, (int*)&g_rt_churn
, TRUE
},
1309 { "rt-ll", no_argument
, (int*)&g_rt_ll
, TRUE
},
1310 { "histogram", no_argument
, (int*)&g_histogram
, TRUE
},
1311 { "verbose", no_argument
, (int*)&g_verbose
, TRUE
},
1312 { "help", no_argument
, NULL
, 'h' },
1313 { NULL
, 0, NULL
, 0 }
1314 /* END IGNORE CODESTYLE */
1317 g_longopts
= longopts
;
1320 while ((ch
= getopt_long(argc
, argv
, "h", longopts
, &option_index
)) != -1) {
1323 /* getopt_long set a variable */
1326 g_do_each_spin
= TRUE
;
1327 g_each_spin_duration_ns
= read_dec_arg();
1330 g_traceworthy_latency_ns
= read_dec_arg();
1333 g_priority
= read_dec_arg();
1336 g_churn_pri
= read_dec_arg();
1338 case OPT_CHURN_COUNT
:
1339 g_churn_count
= read_dec_arg();
1341 case OPT_RT_CHURN_COUNT
:
1342 g_rt_churn_count
= read_dec_arg();
1353 * getopt_long reorders all the options to the beginning of the argv array.
1354 * Jump past them to the non-option arguments.
1361 warnx("Too many non-option arguments passed");
1366 warnx("Missing required <threads> <waketype> <policy> <iterations> arguments");
1372 /* How many threads? */
1373 g_numthreads
= (uint32_t)strtoull(argv
[0], &cp
, 10);
1375 if (cp
== argv
[0] || *cp
) {
1376 errx(EX_USAGE
, "numthreads requires a decimal number, found \"%s\"", argv
[0]);
1379 /* What wakeup pattern? */
1380 g_waketype
= parse_wakeup_pattern(argv
[1]);
1383 g_policy
= parse_thread_policy(argv
[2]);
1386 g_iterations
= (uint32_t)strtoull(argv
[3], &cp
, 10);
1388 if (cp
== argv
[3] || *cp
) {
1389 errx(EX_USAGE
, "numthreads requires a decimal number, found \"%s\"", argv
[3]);
1392 if (g_iterations
< 1) {
1393 errx(EX_USAGE
, "Must have at least one iteration");
1396 if (g_numthreads
== 1 && g_waketype
== WAKE_CHAIN
) {
1397 errx(EX_USAGE
, "chain mode requires more than one thread");
1400 if (g_numthreads
== 1 && g_waketype
== WAKE_HOP
) {
1401 errx(EX_USAGE
, "hop mode requires more than one thread");