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>
58 typedef enum wake_type
{ WAKE_BROADCAST_ONESEM
, WAKE_BROADCAST_PERTHREAD
, WAKE_CHAIN
, WAKE_HOP
} wake_type_t
;
59 typedef enum my_policy_type
{ MY_POLICY_REALTIME
, MY_POLICY_TIMESHARE
, MY_POLICY_FIXEDPRI
} my_policy_type_t
;
61 #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)
62 #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)
63 #define assert_zero_t(tid, error) do { if ((error) != 0) { fprintf(stderr, "[FAIL] Thread %d error %d ", (tid), (error)); assert(error == 0); } } while (0)
65 #define CONSTRAINT_NANOS (20000000ll) /* 20 ms */
66 #define COMPUTATION_NANOS (10000000ll) /* 10 ms */
67 #define TRACEWORTHY_NANOS (10000000ll) /* 10 ms */
72 #define debug_log(args...) printf(args)
74 #define debug_log(args...) do { } while(0)
78 static void* worker_thread(void *arg
);
80 static int thread_setup(uint32_t my_id
);
81 static my_policy_type_t
parse_thread_policy(const char *str
);
82 static void selfexec_with_apptype(int argc
, char *argv
[]);
83 static void parse_args(int argc
, char *argv
[]);
85 static __attribute__((aligned(128))) _Atomic
uint32_t g_done_threads
;
86 static __attribute__((aligned(128))) _Atomic boolean_t g_churn_stop
= FALSE
;
87 static __attribute__((aligned(128))) _Atomic
uint64_t g_churn_stopped_at
= 0;
89 /* Global variables (general) */
90 static uint32_t g_numcpus
;
91 static uint32_t g_numthreads
;
92 static wake_type_t g_waketype
;
93 static policy_t g_policy
;
94 static uint32_t g_iterations
;
95 static struct mach_timebase_info g_mti
;
96 static semaphore_t g_main_sem
;
97 static uint64_t *g_thread_endtimes_abs
;
98 static boolean_t g_verbose
= FALSE
;
99 static boolean_t g_do_affinity
= FALSE
;
100 static uint64_t g_starttime_abs
;
101 static uint32_t g_iteration_sleeptime_us
= 0;
102 static uint32_t g_priority
= 0;
103 static uint32_t g_churn_pri
= 0;
104 static uint32_t g_churn_count
= 0;
106 static pthread_t
* g_churn_threads
= NULL
;
108 /* Threshold for dropping a 'bad run' tracepoint */
109 static uint64_t g_traceworthy_latency_ns
= TRACEWORTHY_NANOS
;
111 /* Have we re-execed to set apptype? */
112 static boolean_t g_seen_apptype
= FALSE
;
114 /* usleep in betweeen iterations */
115 static boolean_t g_do_sleep
= TRUE
;
117 /* Every thread spins until all threads have checked in */
118 static boolean_t g_do_all_spin
= FALSE
;
120 /* Every thread backgrounds temporarily before parking */
121 static boolean_t g_drop_priority
= FALSE
;
123 /* One randomly chosen thread holds up the train for a certain duration. */
124 static boolean_t g_do_one_long_spin
= FALSE
;
125 static uint32_t g_one_long_spin_id
= 0;
126 static uint64_t g_one_long_spin_length_abs
= 0;
127 static uint64_t g_one_long_spin_length_ns
= 0;
129 /* Each thread spins for a certain duration after waking up before blocking again. */
130 static boolean_t g_do_each_spin
= FALSE
;
131 static uint64_t g_each_spin_duration_abs
= 0;
132 static uint64_t g_each_spin_duration_ns
= 0;
134 /* Global variables (broadcast) */
135 static semaphore_t g_broadcastsem
;
136 static semaphore_t g_leadersem
;
137 static semaphore_t g_readysem
;
138 static semaphore_t g_donesem
;
140 /* Global variables (chain) */
141 static semaphore_t
*g_semarr
;
144 abs_to_nanos(uint64_t abstime
)
146 return (uint64_t)(abstime
* (((double)g_mti
.numer
) / ((double)g_mti
.denom
)));
150 nanos_to_abs(uint64_t ns
)
152 return (uint64_t)(ns
* (((double)g_mti
.denom
) / ((double)g_mti
.numer
)));
158 #if defined(__arm__) || defined(__arm64__)
159 asm volatile("yield");
160 #elif defined(__x86_64__) || defined(__i386__)
161 asm volatile("pause");
163 #error Unrecognized architecture
168 churn_thread(__unused
void *arg
)
170 uint64_t spin_count
= 0;
173 * As a safety measure to avoid wedging, we will bail on the spin if
174 * it's been more than 1s after the most recent run start
177 while (g_churn_stop
== FALSE
&&
178 mach_absolute_time() < (g_starttime_abs
+ NSEC_PER_SEC
)) {
183 /* This is totally racy, but only here to detect if anyone stops early */
184 atomic_fetch_add_explicit(&g_churn_stopped_at
, spin_count
, memory_order_relaxed
);
190 create_churn_threads()
192 if (g_churn_count
== 0)
193 g_churn_count
= g_numcpus
- 1;
197 struct sched_param param
= { .sched_priority
= (int)g_churn_pri
};
200 /* Array for churn threads */
201 g_churn_threads
= (pthread_t
*) valloc(sizeof(pthread_t
) * g_churn_count
);
202 assert(g_churn_threads
);
204 if ((err
= pthread_attr_init(&attr
)))
205 errc(EX_OSERR
, err
, "pthread_attr_init");
207 if ((err
= pthread_attr_setschedparam(&attr
, ¶m
)))
208 errc(EX_OSERR
, err
, "pthread_attr_setschedparam");
210 if ((err
= pthread_attr_setschedpolicy(&attr
, SCHED_RR
)))
211 errc(EX_OSERR
, err
, "pthread_attr_setschedpolicy");
213 for (uint32_t i
= 0 ; i
< g_churn_count
; i
++) {
214 pthread_t new_thread
;
216 if ((err
= pthread_create(&new_thread
, &attr
, churn_thread
, NULL
)))
217 errc(EX_OSERR
, err
, "pthread_create");
218 g_churn_threads
[i
] = new_thread
;
221 if ((err
= pthread_attr_destroy(&attr
)))
222 errc(EX_OSERR
, err
, "pthread_attr_destroy");
226 join_churn_threads(void)
228 if (atomic_load_explicit(&g_churn_stopped_at
, memory_order_seq_cst
) != 0)
229 printf("Warning: Some of the churn threads may have stopped early: %lld\n",
232 atomic_store_explicit(&g_churn_stop
, TRUE
, memory_order_seq_cst
);
234 /* Rejoin churn threads */
235 for (uint32_t i
= 0; i
< g_churn_count
; i
++) {
236 errno_t err
= pthread_join(g_churn_threads
[i
], NULL
);
237 if (err
) errc(EX_OSERR
, err
, "pthread_join %d", i
);
242 * Figure out what thread policy to use
244 static my_policy_type_t
245 parse_thread_policy(const char *str
)
247 if (strcmp(str
, "timeshare") == 0) {
248 return MY_POLICY_TIMESHARE
;
249 } else if (strcmp(str
, "realtime") == 0) {
250 return MY_POLICY_REALTIME
;
251 } else if (strcmp(str
, "fixed") == 0) {
252 return MY_POLICY_FIXEDPRI
;
254 errx(EX_USAGE
, "Invalid thread policy \"%s\"", str
);
259 * Figure out what wakeup pattern to use
262 parse_wakeup_pattern(const char *str
)
264 if (strcmp(str
, "chain") == 0) {
266 } else if (strcmp(str
, "hop") == 0) {
268 } else if (strcmp(str
, "broadcast-single-sem") == 0) {
269 return WAKE_BROADCAST_ONESEM
;
270 } else if (strcmp(str
, "broadcast-per-thread") == 0) {
271 return WAKE_BROADCAST_PERTHREAD
;
273 errx(EX_USAGE
, "Invalid wakeup pattern \"%s\"", str
);
281 thread_setup(uint32_t my_id
)
285 thread_time_constraint_policy_data_t pol
;
288 int policy
= SCHED_OTHER
;
289 if (g_policy
== MY_POLICY_FIXEDPRI
)
292 struct sched_param param
= {.sched_priority
= (int)g_priority
};
293 if ((ret
= pthread_setschedparam(pthread_self(), policy
, ¶m
)))
294 errc(EX_OSERR
, ret
, "pthread_setschedparam: %d", my_id
);
298 case MY_POLICY_TIMESHARE
:
300 case MY_POLICY_REALTIME
:
301 /* Hard-coded realtime parameters (similar to what Digi uses) */
303 pol
.constraint
= (uint32_t) nanos_to_abs(CONSTRAINT_NANOS
);
304 pol
.computation
= (uint32_t) nanos_to_abs(COMPUTATION_NANOS
);
305 pol
.preemptible
= 0; /* Ignored by OS */
307 kr
= thread_policy_set(mach_thread_self(), THREAD_TIME_CONSTRAINT_POLICY
,
308 (thread_policy_t
) &pol
, THREAD_TIME_CONSTRAINT_POLICY_COUNT
);
309 mach_assert_zero_t(my_id
, kr
);
311 case MY_POLICY_FIXEDPRI
:
312 ret
= pthread_set_fixedpriority_self();
313 if (ret
) errc(EX_OSERR
, ret
, "pthread_set_fixedpriority_self");
316 errx(EX_USAGE
, "invalid policy type %d", g_policy
);
320 thread_affinity_policy_data_t affinity
;
322 affinity
.affinity_tag
= my_id
% 2;
324 kr
= thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY
,
325 (thread_policy_t
)&affinity
, THREAD_AFFINITY_POLICY_COUNT
);
326 mach_assert_zero_t(my_id
, kr
);
333 * Wait for a wakeup, potentially wake up another of the "0-N" threads,
334 * and notify the main thread when done.
337 worker_thread(void *arg
)
339 uint32_t my_id
= (uint32_t)(uintptr_t)arg
;
342 volatile double x
= 0.0;
343 volatile double y
= 0.0;
345 /* Set policy and so forth */
348 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
351 * Leader thread either wakes everyone up or starts the chain going.
354 /* Give the worker threads undisturbed time to finish before waiting on them */
356 usleep(g_iteration_sleeptime_us
);
358 debug_log("%d Leader thread wait for ready\n", i
);
361 * Wait for everyone else to declare ready
362 * Is there a better way to do this that won't interfere with the rest of the chain?
363 * TODO: Invent 'semaphore wait for N signals'
366 for (uint32_t j
= 0 ; j
< g_numthreads
- 1; j
++) {
367 kr
= semaphore_wait(g_readysem
);
368 mach_assert_zero_t(my_id
, kr
);
371 debug_log("%d Leader thread wait\n", i
);
373 /* Signal main thread and wait for start of iteration */
375 kr
= semaphore_wait_signal(g_leadersem
, g_main_sem
);
376 mach_assert_zero_t(my_id
, kr
);
378 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
380 debug_log("%d Leader thread go\n", i
);
382 assert_zero_t(my_id
, atomic_load_explicit(&g_done_threads
, memory_order_relaxed
));
384 switch (g_waketype
) {
385 case WAKE_BROADCAST_ONESEM
:
386 kr
= semaphore_signal_all(g_broadcastsem
);
387 mach_assert_zero_t(my_id
, kr
);
389 case WAKE_BROADCAST_PERTHREAD
:
390 for (uint32_t j
= 1; j
< g_numthreads
; j
++) {
391 kr
= semaphore_signal(g_semarr
[j
]);
392 mach_assert_zero_t(my_id
, kr
);
396 kr
= semaphore_signal(g_semarr
[my_id
+ 1]);
397 mach_assert_zero_t(my_id
, kr
);
400 kr
= semaphore_wait_signal(g_donesem
, g_semarr
[my_id
+ 1]);
401 mach_assert_zero_t(my_id
, kr
);
406 * Everyone else waits to be woken up,
407 * records when she wakes up, and possibly
411 case WAKE_BROADCAST_ONESEM
:
412 kr
= semaphore_wait_signal(g_broadcastsem
, g_readysem
);
413 mach_assert_zero_t(my_id
, kr
);
415 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
418 case WAKE_BROADCAST_PERTHREAD
:
419 kr
= semaphore_wait_signal(g_semarr
[my_id
], g_readysem
);
420 mach_assert_zero_t(my_id
, kr
);
422 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
426 kr
= semaphore_wait_signal(g_semarr
[my_id
], g_readysem
);
427 mach_assert_zero_t(my_id
, kr
);
429 /* Signal the next thread *after* recording wake time */
431 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
433 if (my_id
< (g_numthreads
- 1)) {
434 kr
= semaphore_signal(g_semarr
[my_id
+ 1]);
435 mach_assert_zero_t(my_id
, kr
);
441 kr
= semaphore_wait_signal(g_semarr
[my_id
], g_readysem
);
442 mach_assert_zero_t(my_id
, kr
);
444 /* Signal the next thread *after* recording wake time */
446 g_thread_endtimes_abs
[my_id
] = mach_absolute_time();
448 if (my_id
< (g_numthreads
- 1)) {
449 kr
= semaphore_wait_signal(g_donesem
, g_semarr
[my_id
+ 1]);
450 mach_assert_zero_t(my_id
, kr
);
452 kr
= semaphore_signal_all(g_donesem
);
453 mach_assert_zero_t(my_id
, kr
);
460 debug_log("Thread %p woke up for iteration %d.\n", pthread_self(), i
);
462 if (g_do_one_long_spin
&& g_one_long_spin_id
== my_id
) {
463 /* One randomly chosen thread holds up the train for a while. */
465 uint64_t endspin
= g_starttime_abs
+ g_one_long_spin_length_abs
;
466 while (mach_absolute_time() < endspin
) {
472 if (g_do_each_spin
) {
473 /* Each thread spins for a certain duration after waking up before blocking again. */
475 uint64_t endspin
= mach_absolute_time() + g_each_spin_duration_abs
;
476 while (mach_absolute_time() < endspin
) {
482 uint32_t done_threads
;
483 done_threads
= atomic_fetch_add_explicit(&g_done_threads
, 1, memory_order_relaxed
) + 1;
485 debug_log("Thread %p new value is %d, iteration %d\n", pthread_self(), done_threads
, i
);
487 if (g_drop_priority
) {
488 /* Drop priority to BG momentarily */
489 errno_t ret
= setpriority(PRIO_DARWIN_THREAD
, 0, PRIO_DARWIN_BG
);
490 if (ret
) errc(EX_OSERR
, ret
, "setpriority PRIO_DARWIN_BG");
494 /* Everyone spins until the last thread checks in. */
496 while (atomic_load_explicit(&g_done_threads
, memory_order_relaxed
) < g_numthreads
) {
502 if (g_drop_priority
) {
503 /* Restore normal priority */
504 errno_t ret
= setpriority(PRIO_DARWIN_THREAD
, 0, 0);
505 if (ret
) errc(EX_OSERR
, ret
, "setpriority 0");
508 debug_log("Thread %p done spinning, iteration %d\n", pthread_self(), i
);
512 /* Give the worker threads undisturbed time to finish before waiting on them */
514 usleep(g_iteration_sleeptime_us
);
516 /* Wait for the worker threads to finish */
517 for (uint32_t i
= 0 ; i
< g_numthreads
- 1; i
++) {
518 kr
= semaphore_wait(g_readysem
);
519 mach_assert_zero_t(my_id
, kr
);
522 /* Tell everyone and the main thread that the last iteration is done */
523 debug_log("%d Leader thread done\n", i
);
525 kr
= semaphore_signal_all(g_main_sem
);
526 mach_assert_zero_t(my_id
, kr
);
528 /* Hold up thread teardown so it doesn't affect the last iteration */
529 kr
= semaphore_wait_signal(g_main_sem
, g_readysem
);
530 mach_assert_zero_t(my_id
, kr
);
537 * Given an array of uint64_t values, compute average, max, min, and standard deviation
540 compute_stats(uint64_t *values
, uint64_t count
, float *averagep
, uint64_t *maxp
, uint64_t *minp
, float *stddevp
)
545 uint64_t _min
= UINT64_MAX
;
549 for (i
= 0; i
< count
; i
++) {
551 _max
= values
[i
] > _max
? values
[i
] : _max
;
552 _min
= values
[i
] < _min
? values
[i
] : _min
;
555 _avg
= ((float)_sum
) / ((float)count
);
558 for (i
= 0; i
< count
; i
++) {
559 _dev
+= powf((((float)values
[i
]) - _avg
), 2);
572 main(int argc
, char **argv
)
578 uint64_t *worst_latencies_ns
;
579 uint64_t *worst_latencies_from_first_ns
;
583 for (int i
= 0; i
< argc
; i
++)
584 if (strcmp(argv
[i
], "--switched_apptype") == 0)
585 g_seen_apptype
= TRUE
;
588 selfexec_with_apptype(argc
, argv
);
590 parse_args(argc
, argv
);
592 srand((unsigned int)time(NULL
));
594 mach_timebase_info(&g_mti
);
596 size_t ncpu_size
= sizeof(g_numcpus
);
597 ret
= sysctlbyname("hw.ncpu", &g_numcpus
, &ncpu_size
, NULL
, 0);
598 if (ret
) err(EX_OSERR
, "Failed sysctlbyname(hw.ncpu)");
601 g_each_spin_duration_abs
= nanos_to_abs(g_each_spin_duration_ns
);
603 /* Configure the long-spin thread to take up half of its computation */
604 if (g_do_one_long_spin
) {
605 g_one_long_spin_length_ns
= COMPUTATION_NANOS
/ 2;
606 g_one_long_spin_length_abs
= nanos_to_abs(g_one_long_spin_length_ns
);
609 /* Estimate the amount of time the cleanup phase needs to back off */
610 g_iteration_sleeptime_us
= g_numthreads
* 20;
612 uint32_t threads_per_core
= (g_numthreads
/ g_numcpus
) + 1;
614 g_iteration_sleeptime_us
+= threads_per_core
* (g_each_spin_duration_ns
/ NSEC_PER_USEC
);
615 if (g_do_one_long_spin
)
616 g_iteration_sleeptime_us
+= g_one_long_spin_length_ns
/ NSEC_PER_USEC
;
618 /* Arrays for threads and their wakeup times */
619 threads
= (pthread_t
*) valloc(sizeof(pthread_t
) * g_numthreads
);
622 size_t endtimes_size
= sizeof(uint64_t) * g_numthreads
;
624 g_thread_endtimes_abs
= (uint64_t*) valloc(endtimes_size
);
625 assert(g_thread_endtimes_abs
);
627 /* Ensure the allocation is pre-faulted */
628 ret
= memset_s(g_thread_endtimes_abs
, endtimes_size
, 0, endtimes_size
);
629 if (ret
) errc(EX_OSERR
, ret
, "memset_s endtimes");
631 size_t latencies_size
= sizeof(uint64_t) * g_iterations
;
633 worst_latencies_ns
= (uint64_t*) valloc(latencies_size
);
634 assert(worst_latencies_ns
);
636 /* Ensure the allocation is pre-faulted */
637 ret
= memset_s(worst_latencies_ns
, latencies_size
, 0, latencies_size
);
638 if (ret
) errc(EX_OSERR
, ret
, "memset_s latencies");
640 worst_latencies_from_first_ns
= (uint64_t*) valloc(latencies_size
);
641 assert(worst_latencies_from_first_ns
);
643 /* Ensure the allocation is pre-faulted */
644 ret
= memset_s(worst_latencies_from_first_ns
, latencies_size
, 0, latencies_size
);
645 if (ret
) errc(EX_OSERR
, ret
, "memset_s latencies_from_first");
647 kr
= semaphore_create(mach_task_self(), &g_main_sem
, SYNC_POLICY_FIFO
, 0);
648 mach_assert_zero(kr
);
650 /* Either one big semaphore or one per thread */
651 if (g_waketype
== WAKE_CHAIN
||
652 g_waketype
== WAKE_BROADCAST_PERTHREAD
||
653 g_waketype
== WAKE_HOP
) {
655 g_semarr
= valloc(sizeof(semaphore_t
) * g_numthreads
);
658 for (uint32_t i
= 0; i
< g_numthreads
; i
++) {
659 kr
= semaphore_create(mach_task_self(), &g_semarr
[i
], SYNC_POLICY_FIFO
, 0);
660 mach_assert_zero(kr
);
663 g_leadersem
= g_semarr
[0];
665 kr
= semaphore_create(mach_task_self(), &g_broadcastsem
, SYNC_POLICY_FIFO
, 0);
666 mach_assert_zero(kr
);
667 kr
= semaphore_create(mach_task_self(), &g_leadersem
, SYNC_POLICY_FIFO
, 0);
668 mach_assert_zero(kr
);
671 if (g_waketype
== WAKE_HOP
) {
672 kr
= semaphore_create(mach_task_self(), &g_donesem
, SYNC_POLICY_FIFO
, 0);
673 mach_assert_zero(kr
);
676 kr
= semaphore_create(mach_task_self(), &g_readysem
, SYNC_POLICY_FIFO
, 0);
677 mach_assert_zero(kr
);
679 atomic_store_explicit(&g_done_threads
, 0, memory_order_relaxed
);
681 /* Create the threads */
682 for (uint32_t i
= 0; i
< g_numthreads
; i
++) {
683 ret
= pthread_create(&threads
[i
], NULL
, worker_thread
, (void*)(uintptr_t)i
);
684 if (ret
) errc(EX_OSERR
, ret
, "pthread_create %d", i
);
687 ret
= setpriority(PRIO_DARWIN_ROLE
, 0, PRIO_DARWIN_ROLE_UI_FOCAL
);
688 if (ret
) errc(EX_OSERR
, ret
, "setpriority");
692 g_starttime_abs
= mach_absolute_time();
695 create_churn_threads();
697 /* Let everyone get settled */
698 kr
= semaphore_wait(g_main_sem
);
699 mach_assert_zero(kr
);
701 /* Give the system a bit more time to settle */
703 usleep(g_iteration_sleeptime_us
);
706 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
708 uint64_t worst_abs
= 0, best_abs
= UINT64_MAX
;
710 if (g_do_one_long_spin
)
711 g_one_long_spin_id
= (uint32_t)rand() % g_numthreads
;
713 debug_log("%d Main thread reset\n", i
);
715 atomic_store_explicit(&g_done_threads
, 0, memory_order_seq_cst
);
717 g_starttime_abs
= mach_absolute_time();
719 /* Fire them off and wait for worker threads to finish */
720 kr
= semaphore_wait_signal(g_main_sem
, g_leadersem
);
721 mach_assert_zero(kr
);
723 debug_log("%d Main thread return\n", i
);
725 assert(atomic_load_explicit(&g_done_threads
, memory_order_relaxed
) == g_numthreads
);
728 * We report the worst latencies relative to start time
729 * and relative to the lead worker thread.
731 for (j
= 0; j
< g_numthreads
; j
++) {
732 uint64_t latency_abs
;
734 latency_abs
= g_thread_endtimes_abs
[j
] - g_starttime_abs
;
735 worst_abs
= worst_abs
< latency_abs
? latency_abs
: worst_abs
;
738 worst_latencies_ns
[i
] = abs_to_nanos(worst_abs
);
741 for (j
= 1; j
< g_numthreads
; j
++) {
742 uint64_t latency_abs
;
744 latency_abs
= g_thread_endtimes_abs
[j
] - g_thread_endtimes_abs
[0];
745 worst_abs
= worst_abs
< latency_abs
? latency_abs
: worst_abs
;
746 best_abs
= best_abs
> latency_abs
? latency_abs
: best_abs
;
749 worst_latencies_from_first_ns
[i
] = abs_to_nanos(worst_abs
);
752 * In the event of a bad run, cut a trace point.
754 if (worst_latencies_from_first_ns
[i
] > g_traceworthy_latency_ns
) {
755 /* Ariadne's ad-hoc test signpost */
756 kdebug_trace(ARIADNEDBG_CODE(0, 0), worst_latencies_from_first_ns
[i
], g_traceworthy_latency_ns
, 0, 0);
759 printf("Worst on this round was %.2f us.\n", ((float)worst_latencies_from_first_ns
[i
]) / 1000.0);
762 /* Give the system a bit more time to settle */
764 usleep(g_iteration_sleeptime_us
);
768 for (uint32_t i
= 0; i
< g_numthreads
; i
++) {
769 ret
= pthread_join(threads
[i
], NULL
);
770 if (ret
) errc(EX_OSERR
, ret
, "pthread_join %d", i
);
774 join_churn_threads();
776 compute_stats(worst_latencies_ns
, g_iterations
, &avg
, &max
, &min
, &stddev
);
777 printf("Results (from a stop):\n");
778 printf("Max:\t\t%.2f us\n", ((float)max
) / 1000.0);
779 printf("Min:\t\t%.2f us\n", ((float)min
) / 1000.0);
780 printf("Avg:\t\t%.2f us\n", avg
/ 1000.0);
781 printf("Stddev:\t\t%.2f us\n", stddev
/ 1000.0);
785 compute_stats(worst_latencies_from_first_ns
, g_iterations
, &avg
, &max
, &min
, &stddev
);
786 printf("Results (relative to first thread):\n");
787 printf("Max:\t\t%.2f us\n", ((float)max
) / 1000.0);
788 printf("Min:\t\t%.2f us\n", ((float)min
) / 1000.0);
789 printf("Avg:\t\t%.2f us\n", avg
/ 1000.0);
790 printf("Stddev:\t\t%.2f us\n", stddev
/ 1000.0);
793 for (uint32_t i
= 0; i
< g_iterations
; i
++) {
794 printf("Iteration %d: %f us\n", i
, worst_latencies_ns
[i
] / 1000.0);
799 free(g_thread_endtimes_abs
);
800 free(worst_latencies_ns
);
801 free(worst_latencies_from_first_ns
);
807 * WARNING: This is SPI specifically intended for use by launchd to start UI
808 * apps. We use it here for a test tool only to opt into QoS using the same
809 * policies. Do not use this outside xnu or libxpc/launchd.
812 selfexec_with_apptype(int argc
, char *argv
[])
815 posix_spawnattr_t attr
;
816 extern char **environ
;
817 char *new_argv
[argc
+ 1 + 1 /* NULL */];
820 uint32_t prog_size
= PATH_MAX
;
822 ret
= _NSGetExecutablePath(prog
, &prog_size
);
823 if (ret
) err(EX_OSERR
, "_NSGetExecutablePath");
825 for (i
=0; i
< argc
; i
++) {
826 new_argv
[i
] = argv
[i
];
829 new_argv
[i
] = "--switched_apptype";
830 new_argv
[i
+1] = NULL
;
832 ret
= posix_spawnattr_init(&attr
);
833 if (ret
) errc(EX_OSERR
, ret
, "posix_spawnattr_init");
835 ret
= posix_spawnattr_setflags(&attr
, POSIX_SPAWN_SETEXEC
);
836 if (ret
) errc(EX_OSERR
, ret
, "posix_spawnattr_setflags");
838 ret
= posix_spawnattr_setprocesstype_np(&attr
, POSIX_SPAWN_PROC_TYPE_APP_DEFAULT
);
839 if (ret
) errc(EX_OSERR
, ret
, "posix_spawnattr_setprocesstype_np");
841 ret
= posix_spawn(NULL
, prog
, NULL
, &attr
, new_argv
, environ
);
842 if (ret
) errc(EX_OSERR
, ret
, "posix_spawn");
846 * Admittedly not very attractive.
848 static void __attribute__((noreturn
))
851 errx(EX_USAGE
, "Usage: %s <threads> <chain | hop | broadcast-single-sem | broadcast-per-thread> "
852 "<realtime | timeshare | fixed> <iterations>\n\t\t"
853 "[--trace <traceworthy latency in ns>] "
854 "[--verbose] [--spin-one] [--spin-all] [--spin-time <nanos>] [--affinity]\n\t\t"
855 "[--no-sleep] [--drop-priority] [--churn-pri <pri>] [--churn-count <n>]",
859 static struct option
* g_longopts
;
860 static int option_index
;
866 /* char* optarg is a magic global */
868 uint32_t arg_val
= (uint32_t)strtoull(optarg
, &cp
, 10);
870 if (cp
== optarg
|| *cp
)
871 errx(EX_USAGE
, "arg --%s requires a decimal number, found \"%s\"",
872 g_longopts
[option_index
].name
, optarg
);
878 parse_args(int argc
, char *argv
[])
889 static struct option longopts
[] = {
890 { "spin-time", required_argument
, NULL
, OPT_SPIN_TIME
},
891 { "trace", required_argument
, NULL
, OPT_TRACE
},
892 { "priority", required_argument
, NULL
, OPT_PRIORITY
},
893 { "churn-pri", required_argument
, NULL
, OPT_CHURN_PRI
},
894 { "churn-count", required_argument
, NULL
, OPT_CHURN_COUNT
},
895 { "switched_apptype", no_argument
, (int*)&g_seen_apptype
, TRUE
},
896 { "spin-one", no_argument
, (int*)&g_do_one_long_spin
, TRUE
},
897 { "spin-all", no_argument
, (int*)&g_do_all_spin
, TRUE
},
898 { "affinity", no_argument
, (int*)&g_do_affinity
, TRUE
},
899 { "no-sleep", no_argument
, (int*)&g_do_sleep
, FALSE
},
900 { "drop-priority", no_argument
, (int*)&g_drop_priority
, TRUE
},
901 { "verbose", no_argument
, (int*)&g_verbose
, TRUE
},
902 { "help", no_argument
, NULL
, 'h' },
906 g_longopts
= longopts
;
909 while ((ch
= getopt_long(argc
, argv
, "h", longopts
, &option_index
)) != -1) {
912 /* getopt_long set a variable */
915 g_do_each_spin
= TRUE
;
916 g_each_spin_duration_ns
= read_dec_arg();
919 g_traceworthy_latency_ns
= read_dec_arg();
922 g_priority
= read_dec_arg();
925 g_churn_pri
= read_dec_arg();
927 case OPT_CHURN_COUNT
:
928 g_churn_count
= read_dec_arg();
939 * getopt_long reorders all the options to the beginning of the argv array.
940 * Jump past them to the non-option arguments.
947 warnx("Too many non-option arguments passed");
952 warnx("Missing required <threads> <waketype> <policy> <iterations> arguments");
958 /* How many threads? */
959 g_numthreads
= (uint32_t)strtoull(argv
[0], &cp
, 10);
961 if (cp
== argv
[0] || *cp
)
962 errx(EX_USAGE
, "numthreads requires a decimal number, found \"%s\"", argv
[0]);
964 if (g_numthreads
< 1)
965 errx(EX_USAGE
, "Must use at least one thread");
967 /* What wakeup pattern? */
968 g_waketype
= parse_wakeup_pattern(argv
[1]);
971 g_policy
= parse_thread_policy(argv
[2]);
974 g_iterations
= (uint32_t)strtoull(argv
[3], &cp
, 10);
976 if (cp
== argv
[3] || *cp
)
977 errx(EX_USAGE
, "numthreads requires a decimal number, found \"%s\"", argv
[3]);
979 if (g_iterations
< 1)
980 errx(EX_USAGE
, "Must have at least one iteration");
982 if (g_numthreads
== 1 && g_waketype
== WAKE_CHAIN
)
983 errx(EX_USAGE
, "chain mode requires more than one thread");
985 if (g_numthreads
== 1 && g_waketype
== WAKE_HOP
)
986 errx(EX_USAGE
, "hop mode requires more than one thread");