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@
32 #include <sys/syscall.h>
33 #include <sys/types.h>
34 #include <sys/ptrace.h>
35 #include <semaphore.h>
43 #include <libkern/OSAtomic.h>
45 #include <mach/mach_time.h>
46 #include <mach/mach.h>
47 #include <mach/task.h>
48 #include <mach/semaphore.h>
50 typedef enum my_policy_type
{ MY_POLICY_REALTIME
, MY_POLICY_TIMESHARE
, MY_POLICY_FIXEDPRI
} my_policy_type_t
;
52 #define DEFAULT_MAX_SLEEP_NS 2000000000ll /* Two seconds */
53 #define CONSTRAINT_NANOS (20000000ll) /* 20 ms */
54 #define COMPUTATION_NANOS (10000000ll) /* 10 ms */
56 struct mach_timebase_info g_mti
;
58 #define assert(truth, label) do { if(!(truth)) { printf("Thread %p: failure on line %d\n", pthread_self(), __LINE__); goto label; } } while (0)
60 struct second_thread_args
{
61 semaphore_t wakeup_semaphore
;
62 semaphore_t return_semaphore
;
65 double *wakeup_second_jitter_arr
;
66 uint64_t woke_on_same_cpu
;
68 volatile uint64_t last_poke_time
;
72 extern int cpu_number(void);
75 second_thread(void *args
);
80 printf("Usage: jitter [-w] [-s <random seed>] [-n <min sleep, ns>] [-m <max sleep, ns>] <realtime | timeshare | fixed> <num iterations> <traceworthy jitter, ns>\n");
84 parse_thread_policy(const char *str
)
86 if (strcmp(str
, "timeshare") == 0) {
87 return MY_POLICY_TIMESHARE
;
88 } else if (strcmp(str
, "realtime") == 0) {
89 return MY_POLICY_REALTIME
;
90 } else if (strcmp(str
, "fixed") == 0) {
91 return MY_POLICY_FIXEDPRI
;
93 printf("Invalid thread policy %s\n", str
);
99 thread_setup(my_policy_type_t pol
)
104 case MY_POLICY_TIMESHARE
:
108 case MY_POLICY_REALTIME
:
110 thread_time_constraint_policy_data_t pol
;
112 /* Hard-coded realtime parameters (similar to what Digi uses) */
114 pol
.constraint
= CONSTRAINT_NANOS
* g_mti
.denom
/ g_mti
.numer
;
115 pol
.computation
= COMPUTATION_NANOS
* g_mti
.denom
/ g_mti
.numer
;
116 pol
.preemptible
= 0; /* Ignored by OS */
118 res
= thread_policy_set(mach_thread_self(), THREAD_TIME_CONSTRAINT_POLICY
, (thread_policy_t
) &pol
, THREAD_TIME_CONSTRAINT_POLICY_COUNT
);
119 assert(res
== 0, fail
);
122 case MY_POLICY_FIXEDPRI
:
124 thread_extended_policy_data_t pol
;
127 res
= thread_policy_set(mach_thread_self(), THREAD_EXTENDED_POLICY
, (thread_policy_t
) &pol
, THREAD_EXTENDED_POLICY_COUNT
);
128 assert(res
== 0, fail
);
133 printf("invalid policy type\n");
144 get_random_sleep_length_abs_ns(uint64_t min_sleep_ns
, uint64_t max_sleep_ns
)
148 tmp
= (uint32_t)random();
150 tmp
|= (uint32_t)random();
152 /* Now use the random number to sleep amount within the window */
153 tmp
%= (max_sleep_ns
- min_sleep_ns
);
155 return min_sleep_ns
+ tmp
;
159 compute_stats(double *values
, uint64_t count
, double *average_magnitudep
, double *maxp
, double *minp
, double *stddevp
)
164 double _min
= (double)INT64_MAX
;
168 for (i
= 0; i
< count
; i
++) {
169 _sum
+= fabs(values
[i
]);
170 _max
= values
[i
] > _max
? values
[i
] : _max
;
171 _min
= values
[i
] < _min
? values
[i
] : _min
;
174 _avg
= _sum
/ (double)count
;
177 for (i
= 0; i
< count
; i
++) {
178 _dev
+= pow((values
[i
] - _avg
), 2);
184 *average_magnitudep
= _avg
;
191 print_stats_us(const char *label
, double avg
, double max
, double min
, double stddev
)
193 printf("Max %s: %.1lfus\n", label
, max
/ 1000.0 * (((double)g_mti
.numer
) / ((double)g_mti
.denom
)));
194 printf("Min %s: %.1lfus\n", label
, min
/ 1000.0 * (((double)g_mti
.numer
) / ((double)g_mti
.denom
)));
195 printf("Avg magnitude of %s: %.1lfus\n", label
, avg
/ 1000.0 * (((double)g_mti
.numer
) / ((double)g_mti
.denom
)));
196 printf("Stddev: %.1lfus\n", stddev
/ 1000.0 * (((double)g_mti
.numer
) / ((double)g_mti
.denom
)));
201 print_stats_fract(const char *label
, double avg
, double max
, double min
, double stddev
)
203 printf("Max %s jitter: %.1lf%%\n", label
, max
* 100);
204 printf("Min %s jitter: %.1lf%%\n", label
, min
* 100);
205 printf("Avg %s jitter: %.1lf%%\n", label
, avg
* 100);
206 printf("Stddev: %.1lf%%\n", stddev
* 100);
211 main(int argc
, char **argv
)
213 uint64_t iterations
, i
;
214 double *jitter_arr
, *fraction_arr
;
215 double *wakeup_second_jitter_arr
;
216 uint64_t target_time
;
217 uint64_t sleep_length_abs
;
218 uint64_t min_sleep_ns
= 0;
219 uint64_t max_sleep_ns
= DEFAULT_MAX_SLEEP_NS
;
221 unsigned random_seed
;
222 boolean_t need_seed
= TRUE
;
226 my_policy_type_t pol
;
227 boolean_t wakeup_second_thread
= FALSE
;
228 semaphore_t wakeup_semaphore
, return_semaphore
;
230 double avg
, stddev
, max
, min
;
231 double avg_fract
, stddev_fract
, max_fract
, min_fract
;
234 struct second_thread_args secargs
;
237 mach_timebase_info(&g_mti
);
241 while ((ch
= getopt(argc
, argv
, "m:n:hs:w")) != -1 && ch
!= '?') {
244 /* Specified seed for random)() */
245 random_seed
= (unsigned)atoi(optarg
);
246 srandom(random_seed
);
250 /* How long per timer? */
251 max_sleep_ns
= strtoull(optarg
, NULL
, 10);
254 /* How long per timer? */
255 min_sleep_ns
= strtoull(optarg
, NULL
, 10);
258 /* After each timed wait, wakeup another thread */
259 wakeup_second_thread
= TRUE
;
266 fprintf(stderr
, "Got unexpected result from getopt().\n");
280 if (min_sleep_ns
>= max_sleep_ns
) {
289 /* What scheduling policy? */
290 pol
= parse_thread_policy(argv
[0]);
292 /* How many timers? */
293 iterations
= strtoull(argv
[1], NULL
, 10);
295 /* How much jitter is so extreme that we should cut a trace point */
296 too_much
= strtoull(argv
[2], NULL
, 10);
299 jitter_arr
= (double*)malloc(sizeof(*jitter_arr
) * iterations
);
300 if (jitter_arr
== NULL
) {
301 printf("Couldn't allocate array to store results.\n");
305 fraction_arr
= (double*)malloc(sizeof(*fraction_arr
) * iterations
);
306 if (fraction_arr
== NULL
) {
307 printf("Couldn't allocate array to store results.\n");
311 if (wakeup_second_thread
) {
313 wakeup_second_jitter_arr
= (double*)malloc(sizeof(*jitter_arr
) * iterations
);
314 if (wakeup_second_jitter_arr
== NULL
) {
315 printf("Couldn't allocate array to store results.\n");
319 kret
= semaphore_create(mach_task_self(), &wakeup_semaphore
, SYNC_POLICY_FIFO
, 0);
320 if (kret
!= KERN_SUCCESS
) {
321 printf("Couldn't allocate semaphore %d\n", kret
);
325 kret
= semaphore_create(mach_task_self(), &return_semaphore
, SYNC_POLICY_FIFO
, 0);
326 if (kret
!= KERN_SUCCESS
) {
327 printf("Couldn't allocate semaphore %d\n", kret
);
332 secargs
.wakeup_semaphore
= wakeup_semaphore
;
333 secargs
.return_semaphore
= return_semaphore
;
334 secargs
.iterations
= iterations
;
336 secargs
.wakeup_second_jitter_arr
= wakeup_second_jitter_arr
;
337 secargs
.woke_on_same_cpu
= 0;
338 secargs
.too_much
= too_much
;
339 secargs
.last_poke_time
= 0ULL;
342 res
= pthread_create(§hread
, NULL
, second_thread
, &secargs
);
344 err(1, "pthread_create");
347 sleep(1); /* Time for other thread to start up */
350 /* Set scheduling policy */
351 res
= thread_setup(pol
);
353 printf("Couldn't set thread policy.\n");
358 * Repeatedly pick a random timer length and
359 * try to sleep exactly that long
361 for (i
= 0; i
< iterations
; i
++) {
362 sleep_length_abs
= (uint64_t) (get_random_sleep_length_abs_ns(min_sleep_ns
, max_sleep_ns
) * (((double)g_mti
.denom
) / ((double)g_mti
.numer
)));
363 target_time
= mach_absolute_time() + sleep_length_abs
;
366 kret
= mach_wait_until(target_time
);
367 wake_time
= mach_absolute_time();
369 jitter_arr
[i
] = (double)(wake_time
- target_time
);
370 fraction_arr
[i
] = jitter_arr
[i
] / ((double)sleep_length_abs
);
372 /* Too much: cut a tracepoint for a debugger */
373 if (jitter_arr
[i
] >= too_much
) {
374 syscall(SYS_kdebug_trace
, 0xeeeeeeee, 0, 0, 0, 0);
377 if (wakeup_second_thread
) {
378 secargs
.last_poke_time
= mach_absolute_time();
379 secargs
.cpuno
= cpu_number();
381 kret
= semaphore_signal(wakeup_semaphore
);
382 if (kret
!= KERN_SUCCESS
) {
383 errx(1, "semaphore_signal");
386 kret
= semaphore_wait(return_semaphore
);
387 if (kret
!= KERN_SUCCESS
) {
388 errx(1, "semaphore_wait");
395 * Compute statistics and output results.
397 compute_stats(jitter_arr
, iterations
, &avg
, &max
, &min
, &stddev
);
398 compute_stats(fraction_arr
, iterations
, &avg_fract
, &max_fract
, &min_fract
, &stddev_fract
);
401 print_stats_us("jitter", avg
, max
, min
, stddev
);
402 print_stats_fract("%", avg_fract
, max_fract
, min_fract
, stddev_fract
);
404 if (wakeup_second_thread
) {
406 res
= pthread_join(secthread
, NULL
);
408 err(1, "pthread_join");
411 compute_stats(wakeup_second_jitter_arr
, iterations
, &avg
, &max
, &min
, &stddev
);
414 print_stats_us("second jitter", avg
, max
, min
, stddev
);
417 printf("%llu/%llu (%.1f%%) wakeups on same CPU\n", secargs
.woke_on_same_cpu
, iterations
,
418 100.0*((double)secargs
.woke_on_same_cpu
)/iterations
);
425 second_thread(void *args
)
427 struct second_thread_args
*secargs
= (struct second_thread_args
*)args
;
434 /* Set scheduling policy */
435 res
= thread_setup(secargs
->pol
);
437 printf("Couldn't set thread policy.\n");
442 * Repeatedly pick a random timer length and
443 * try to sleep exactly that long
445 for (i
= 0; i
< secargs
->iterations
; i
++) {
447 /* Wake up when poked by main thread */
448 kret
= semaphore_wait(secargs
->wakeup_semaphore
);
449 if (kret
!= KERN_SUCCESS
) {
450 errx(1, "semaphore_wait %d", kret
);
453 wake_time
= mach_absolute_time();
454 cpuno
= cpu_number();
455 if (wake_time
< secargs
->last_poke_time
) {
456 /* Woke in past, unsynchronized mach_absolute_time()? */
458 errx(1, "woke in past %llu (%d) < %llu (%d)", wake_time
, cpuno
, secargs
->last_poke_time
, secargs
->cpuno
);
461 if (cpuno
== secargs
->cpuno
) {
462 secargs
->woke_on_same_cpu
++;
465 secargs
->wakeup_second_jitter_arr
[i
] = (double)(wake_time
- secargs
->last_poke_time
);
467 /* Too much: cut a tracepoint for a debugger */
468 if (secargs
->wakeup_second_jitter_arr
[i
] >= secargs
->too_much
) {
469 syscall(SYS_kdebug_trace
, 0xeeeeeeef, 0, 0, 0, 0);
472 kret
= semaphore_signal(secargs
->return_semaphore
);
473 if (kret
!= KERN_SUCCESS
) {
474 errx(1, "semaphore_signal %d", kret
);