xref: /xnu-8019.80.24/tests/ktrace/kperf_tests.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
1 // Copyright (c) 2017-2021 Apple Inc.  All rights reserved.
2 
3 #include <darwintest.h>
4 #include <darwintest_utils.h>
5 #include <dispatch/dispatch.h>
6 #include <inttypes.h>
7 #include <ktrace/session.h>
8 #include <ktrace/private.h>
9 #include <sys/kdebug.h>
10 #include <sys/syscall.h>
11 #include <kperf/kpc.h>
12 #include <kperf/kperf.h>
13 #include <kperfdata/kpdecode.h>
14 #include <os/assumes.h>
15 #include <stdint.h>
16 #include <sys/sysctl.h>
17 
18 #include "kperf_helpers.h"
19 #include "ktrace_helpers.h"
20 #include "ktrace_meta.h"
21 #include "../drop_priv.h"
22 
23 #define MAX_CPUS    64
24 #define MAX_THREADS 64
25 
26 volatile static bool running_threads = true;
27 
28 static void *
spinning_thread(void * semp)29 spinning_thread(void *semp)
30 {
31 	T_QUIET;
32 	T_ASSERT_NOTNULL(semp, "semaphore passed to thread should not be NULL");
33 	dispatch_semaphore_signal(*(dispatch_semaphore_t *)semp);
34 
35 	while (running_threads) {
36 		;
37 	}
38 	return NULL;
39 }
40 
41 #define PERF_STK_KHDR   UINT32_C(0x25020014)
42 #define PERF_STK_UHDR   UINT32_C(0x25020018)
43 #define PERF_TMR_FIRE   KDBG_EVENTID(DBG_PERF, 3, 0)
44 #define PERF_TMR_HNDLR  KDBG_EVENTID(DBG_PERF, 3, 2)
45 #define PERF_TMR_PEND   KDBG_EVENTID(DBG_PERF, 3, 3)
46 #define PERF_TMR_SKIP   KDBG_EVENTID(DBG_PERF, 3, 4)
47 #define PERF_KPC_CONFIG KDBG_EVENTID(DBG_PERF, 6, 4)
48 #define PERF_KPC_REG    KDBG_EVENTID(DBG_PERF, 6, 5)
49 #define PERF_KPC_REG32  KDBG_EVENTID(DBG_PERF, 6, 7)
50 #define PERF_INSTR_DATA KDBG_EVENTID(DBG_PERF, 1, 17)
51 #define PERF_EVENT      KDBG_EVENTID(DBG_PERF, 0, 0)
52 #define PERF_DISPLABEL  KDBG_EVENTID(DBG_PERF, 1, 23)
53 #define PERF_DISPSAMPLE KDBG_EVENTID(DBG_PERF, 1, 10)
54 
55 #define SCHED_DISPATCH KDBG_EVENTID(DBG_MACH, DBG_MACH_SCHED, MACH_DISPATCH)
56 #define SCHED_SWITCH KDBG_EVENTID(DBG_MACH, DBG_MACH_SCHED, MACH_SCHED)
57 #define SCHED_HANDOFF KDBG_EVENTID(DBG_MACH, DBG_MACH_SCHED, MACH_STACK_HANDOFF)
58 #define SCHED_IDLE KDBG_EVENTID(DBG_MACH, DBG_MACH_SCHED, MACH_IDLE)
59 
60 #define MP_CPUS_CALL UINT32_C(0x1900004)
61 
62 #define DISPATCH_AFTER_EVENT UINT32_C(0xfefffffc)
63 #define TIMEOUT_SECS 10
64 
65 #define TIMER_PERIOD_NS (1 * NSEC_PER_MSEC)
66 
67 static void
start_tracing_with_timeout(ktrace_session_t s,unsigned int timeout_secs)68 start_tracing_with_timeout(ktrace_session_t s, unsigned int timeout_secs)
69 {
70 	// Only set the timeout after we've seen an event that was traced by us.
71 	// This helps set a reasonable timeout after we're guaranteed to get a
72 	// few events.
73 	dispatch_queue_t q = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);
74 
75 	ktrace_events_single(s, DISPATCH_AFTER_EVENT,
76 	    ^(__unused struct trace_point *tp)
77 	{
78 		T_LOG("arming timer to stop tracing after %d seconds", timeout_secs);
79 		dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
80 		    timeout_secs * NSEC_PER_SEC), q, ^{
81 			T_LOG("ending tracing due to timeout");
82 			ktrace_end(s, 0);
83 		});
84 	});
85 	ktrace_set_collection_interval(s, 100);
86 
87 	T_ASSERT_POSIX_ZERO(ktrace_start(s, q), "start ktrace");
88 
89 	kdebug_trace(DISPATCH_AFTER_EVENT, 0, 0, 0, 0);
90 	T_LOG("trace point emitted");
91 }
92 
93 static void
configure_kperf_timer_samplers(uint64_t period_ns,uint32_t samplers)94 configure_kperf_timer_samplers(uint64_t period_ns, uint32_t samplers)
95 {
96 	T_SETUPBEGIN;
97 
98 	(void)kperf_action_count_set(1);
99 	T_QUIET;
100 	T_ASSERT_POSIX_SUCCESS(kperf_action_samplers_set(1, samplers),
101 	    NULL);
102 	(void)kperf_timer_count_set(1);
103 	T_QUIET;
104 	T_ASSERT_POSIX_SUCCESS(kperf_timer_period_set(0,
105 	    kperf_ns_to_ticks(period_ns)), NULL);
106 	T_QUIET;
107 	T_ASSERT_POSIX_SUCCESS(kperf_timer_action_set(0, 1), NULL);
108 
109 	T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), "start kperf sampling");
110 
111 	T_SETUPEND;
112 }
113 
114 static double
timestamp_secs(ktrace_session_t s,uint64_t timestamp)115 timestamp_secs(ktrace_session_t s, uint64_t timestamp)
116 {
117 	uint64_t ns = 0;
118 	T_QUIET;
119 	T_ASSERT_POSIX_ZERO(ktrace_convert_timestamp_to_nanoseconds(s, timestamp,
120 	    &ns), NULL);
121 	return (double)ns / NSEC_PER_SEC;
122 }
123 
124 #pragma mark - timers
125 
126 // Ensure that kperf is correctly sampling CPUs that are actively scheduling by
127 // bringing up threads and ensuring that threads on-core are sampled by each
128 // timer fire.
129 
130 T_DECL(kperf_sample_active_cpus,
131     "make sure that kperf samples all active CPUs")
132 {
133 	start_controlling_ktrace();
134 
135 	T_SETUPBEGIN;
136 
137 	int ncpus = dt_ncpu();
138 	T_QUIET;
139 	T_ASSERT_LT(ncpus, MAX_CPUS,
140 	    "only supports up to %d CPUs", MAX_CPUS);
141 	T_LOG("found %d CPUs", ncpus);
142 
143 	int nthreads = ncpus - 1;
144 	T_QUIET;
145 	T_ASSERT_LT(nthreads, MAX_THREADS,
146 	    "only supports up to %d threads", MAX_THREADS);
147 
148 	static pthread_t threads[MAX_THREADS];
149 
150 	ktrace_session_t s = ktrace_session_create();
151 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(s, "ktrace_session_create");
152 	ktrace_set_collection_interval(s, 100);
153 
154 	__block uint64_t nfires = 0;
155 	__block uint64_t nsamples = 0;
156 	static uint64_t idle_tids[MAX_CPUS] = { 0 };
157 	__block double sum_saturation = 0;
158 	__block uint64_t last_nsamples = 0;
159 
160 	// As a test debugging aid, take an additonal argument that specifies the
161 	// number of fires to stop tracing after.  This also turns on additional
162 	// logging of scheduler trace events.
163 	int stopafter = 0;
164 	if (argc > 0) {
165 		stopafter = atoi(argv[0]);
166 		if (stopafter < 0) {
167 			T_ASSERT_FAIL("argument must be positive");
168 		}
169 	}
170 
171 	static uint64_t first_timestamp = 0;
172 	static uint64_t last_timestamp = 0;
173 	ktrace_events_any(s, ^(struct trace_point *tp) {
174 		if (first_timestamp == 0) {
175 			first_timestamp = tp->timestamp;
176 		}
177 		last_timestamp = tp->timestamp;
178 	});
179 
180 	ktrace_set_completion_handler(s, ^{
181 		T_LOG("stopping threads");
182 
183 		running_threads = false;
184 
185 		for (int i = 0; i < nthreads; i++) {
186 		        T_QUIET;
187 		        T_ASSERT_POSIX_ZERO(pthread_join(threads[i], NULL), NULL);
188 		}
189 
190 		double saturation = sum_saturation / nfires * 100;
191 
192 		T_LOG("over %.1f seconds, saw %" PRIu64 " timer fires, %" PRIu64
193 			" samples, %g samples/fire, %.2f%% saturation",
194 			timestamp_secs(s, last_timestamp - first_timestamp), nfires,
195 			nsamples, (double)nsamples / (double)nfires, saturation);
196 		T_ASSERT_GT(saturation, 95.0,
197 		    "saw reasonable percentage of full samples");
198 
199 		T_END;
200 	});
201 
202 	// Track which threads are running on each CPU.
203 	static uint64_t tids_on_cpu[MAX_CPUS] = { 0 };
204 	void (^switch_cb)(struct trace_point *, const char *name) =
205 	    ^(struct trace_point *tp, const char *name) {
206 		uint64_t new_thread = tp->arg2;
207 
208 		if (idle_tids[tp->cpuid] != new_thread) {
209 			tids_on_cpu[tp->cpuid] = new_thread;
210 		}
211 
212 		if (stopafter) {
213 			T_LOG("%.7g: %s on %d: %llx", timestamp_secs(s, tp->timestamp),
214 			    name, tp->cpuid, tp->arg2);
215 		}
216 	};
217 
218 	ktrace_events_single(s, SCHED_SWITCH, ^(struct trace_point *tp) {
219 		switch_cb(tp, "switch");
220 	});
221 	ktrace_events_single(s, SCHED_HANDOFF, ^(struct trace_point *tp) {
222 		switch_cb(tp, "hndoff");
223 	});
224 
225 	// Determine the thread IDs of the idle threads on each CPU.
226 	ktrace_events_single(s, SCHED_IDLE, ^(struct trace_point *tp) {
227 		if (tp->debugid & DBG_FUNC_END) {
228 			return;
229 		}
230 		tids_on_cpu[tp->cpuid] = 0;
231 		idle_tids[tp->cpuid] = tp->threadid;
232 		if (stopafter) {
233 			T_LOG("%.7g: idle on %d: %llx", timestamp_secs(s, tp->timestamp),
234 			    tp->cpuid, tp->threadid);
235 		}
236 	});
237 
238 	// On each timer fire, go through all the cores and mark any threads
239 	// that should be sampled.
240 
241 	__block int last_fire_cpu = -1;
242 	static bool sample_missing[MAX_CPUS] = { false };
243 	static uint64_t tids_snap[MAX_CPUS] = { 0 };
244 	__block int nexpected = 0;
245 	__block int nextra = 0;
246 	__block int nidles = 0;
247 
248 	ktrace_events_single(s, PERF_TMR_FIRE, ^(struct trace_point *tp) {
249 		T_QUIET; T_ASSERT_EQ((tp->debugid & DBG_FUNC_START), 0,
250 		    "no timer fire start events are allowed");
251 		int last_expected = nexpected;
252 		nfires++;
253 
254 		nexpected = 0;
255 		for (int i = 0; i < ncpus; i++) {
256 			if (sample_missing[i]) {
257 				T_LOG("missed sample on CPU %d for thread %#llx from "
258 				    "timer on CPU %d (expected %d samples)",
259 				    tp->cpuid, tids_snap[i], last_fire_cpu, last_expected);
260 				sample_missing[i] = false;
261 			}
262 
263 			if (tids_on_cpu[i] != 0) {
264 				tids_snap[i] = tids_on_cpu[i];
265 				sample_missing[i] = true;
266 				nexpected++;
267 			}
268 		}
269 		if (stopafter) {
270 			T_LOG("%.7g: FIRE on %d: %d extra, %d idles",
271 			    timestamp_secs(s, tp->timestamp), tp->cpuid, nextra, nidles);
272 		}
273 
274 		if (nfires == 1) {
275 			return;
276 		}
277 
278 		if (last_expected == 0) {
279 			sum_saturation += 1;
280 		} else {
281 			sum_saturation += (double)(nsamples - last_nsamples) /
282 			    last_expected;
283 		}
284 		last_nsamples = nsamples;
285 		nextra = 0;
286 		nidles = 0;
287 
288 		T_QUIET;
289 		T_ASSERT_LT((int)tp->cpuid, ncpus,
290 		    "timer fire should not occur on an IOP");
291 		last_fire_cpu = (int)tp->cpuid;
292 
293 		if (stopafter && (uint64_t)stopafter == nfires) {
294 			ktrace_end(s, 1);
295 		}
296 	});
297 
298 	// On the timer handler for each CPU, unset the missing sample bitmap.
299 
300 	ktrace_events_single(s, PERF_TMR_HNDLR, ^(struct trace_point *tp) {
301 		nsamples++;
302 		if ((int)tp->cpuid > ncpus) {
303 		        // Skip IOPs; they're not scheduling any relevant threads.
304 		        return;
305 		}
306 
307 		if (!sample_missing[tp->cpuid] && idle_tids[tp->cpuid] != 0) {
308 			T_LOG("sampled additional thread %llx on CPU %d", tp->threadid,
309 			    tp->cpuid);
310 			nextra++;
311 		}
312 		if (tp->threadid == idle_tids[tp->cpuid]) {
313 			T_LOG("sampled idle thread on CPU %d", tp->cpuid);
314 			nidles++;
315 		}
316 		sample_missing[tp->cpuid] = false;
317 	});
318 
319 	configure_kperf_timer_samplers(TIMER_PERIOD_NS, KPERF_SAMPLER_KSTACK);
320 
321 	T_SETUPEND;
322 
323 	start_tracing_with_timeout(s, TIMEOUT_SECS);
324 
325 	// Create threads to bring up all of the CPUs.
326 
327 	dispatch_semaphore_t thread_spinning = dispatch_semaphore_create(0);
328 
329 	for (int i = 0; i < nthreads; i++) {
330 		T_QUIET;
331 		T_ASSERT_POSIX_ZERO(
332 			pthread_create(&threads[i], NULL, &spinning_thread,
333 			&thread_spinning), NULL);
334 		dispatch_semaphore_wait(thread_spinning, DISPATCH_TIME_FOREVER);
335 	}
336 
337 	T_LOG("spun up %d thread%s", nthreads, nthreads == 1 ? "" : "s");
338 
339 	dispatch_main();
340 }
341 
342 #define FIRES_THRESHOLD (5000)
343 
344 T_DECL(kperf_timer_fires_enough_times,
345     "ensure the correct number of timers fire in a period of time")
346 {
347 	start_controlling_ktrace();
348 
349 	dispatch_semaphore_t thread_spinning = dispatch_semaphore_create(0);
350 
351 	ktrace_session_t s = ktrace_session_create();
352 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(s, "ktrace_session_create");
353 	ktrace_set_collection_interval(s, 100);
354 
355 	__block uint64_t nfires = 0;
356 	__block uint64_t first_fire_ns = 0;
357 	__block uint64_t last_fire_ns = 0;
358 
359 	int ncpus = dt_ncpu();
360 
361 	ktrace_events_single(s, PERF_TMR_FIRE, ^(struct trace_point *tp) {
362 		nfires++;
363 		if (first_fire_ns == 0) {
364 			ktrace_convert_timestamp_to_nanoseconds(s, tp->timestamp,
365 			    &first_fire_ns);
366 		}
367 		ktrace_convert_timestamp_to_nanoseconds(s, tp->timestamp,
368 		    &last_fire_ns);
369 
370 		T_QUIET; T_ASSERT_LT((int)tp->cpuid, ncpus,
371 		    "timer fire should not occur on an IOP");
372 		if (nfires >= FIRES_THRESHOLD) {
373 			ktrace_end(s, 1);
374 		}
375 	});
376 
377 	configure_kperf_timer_samplers(TIMER_PERIOD_NS, KPERF_SAMPLER_KSTACK);
378 
379 	pthread_t thread;
380  	T_QUIET;
381 	T_ASSERT_POSIX_ZERO(pthread_create(&thread, NULL, &spinning_thread,
382 	    &thread_spinning), NULL);
383 	dispatch_semaphore_wait(thread_spinning, DISPATCH_TIME_FOREVER);
384 
385 	ktrace_set_completion_handler(s, ^{
386 		running_threads = false;
387 
388 		double duration_secs = (double)(last_fire_ns - first_fire_ns) /
389 		    NSEC_PER_SEC;
390 		T_LOG("stopping thread after %.2f seconds", duration_secs);
391 
392 		T_QUIET; T_ASSERT_POSIX_ZERO(pthread_join(thread, NULL), NULL);
393 
394 		T_LOG("saw %" PRIu64 " timer fires (%g fires/second)", nfires,
395 		    (double)nfires / (double)duration_secs);
396 		double expected_nfires = duration_secs * NSEC_PER_SEC / TIMER_PERIOD_NS;
397 		T_LOG("expecting %g timer fires", expected_nfires);
398 		double nfires_seen_pct = expected_nfires / nfires * 100;
399 		T_ASSERT_GT(nfires_seen_pct, 95.0,
400 		    "saw reasonable number of missed timer fires");
401 		T_ASSERT_LT(nfires_seen_pct, 105.0,
402 			"saw reasonable number of extra timer fires");
403 
404 		T_END;
405 	});
406 
407 	start_tracing_with_timeout(s, TIMEOUT_SECS);
408 
409 	dispatch_main();
410 }
411 
412 // kperf_timer_not_oversampling ensures that the profiling timer fires are
413 // spaced apart by the programmed timer period.  Otherwise, tools that rely on
414 // sample count as a proxy for CPU usage will over-estimate.
415 
416 #define FIRE_PERIOD_THRESHOLD_NS \
417 		(TIMER_PERIOD_NS - (uint64_t)(TIMER_PERIOD_NS * 0.05))
418 
419 struct cirq {
420 	unsigned int nslots;
421 	unsigned int tail_slot;
422 	unsigned int slot_size;
423 };
424 
425 #define CIRQ_INIT(TYPE, NSLOTS) \
426 	(struct cirq){ \
427 		.nslots = NSLOTS, .tail_slot = 0, .slot_size = sizeof(TYPE), \
428 	}
429 
430 static inline void *
cirq_get(struct cirq * cq,unsigned int i)431 cirq_get(struct cirq *cq, unsigned int i)
432 {
433 	return (char *)cq + sizeof(*cq) + (cq->slot_size * i);
434 }
435 
436 static void *
cirq_top(void * vcq)437 cirq_top(void *vcq)
438 {
439 	struct cirq *cq = vcq;
440 	unsigned int tail_slot = cq->tail_slot;
441 	unsigned int top_slot = (tail_slot > 0 ? tail_slot : cq->nslots) - 1;
442 	return cirq_get(cq, top_slot);
443 }
444 
445 static void *
cirq_push(void * vcq)446 cirq_push(void *vcq)
447 {
448 	struct cirq *cq = vcq;
449 	unsigned int tail_slot = cq->tail_slot;
450 	unsigned int next_slot = tail_slot == cq->nslots - 1 ? 0 : tail_slot + 1;
451 	cq->tail_slot = next_slot;
452 	return cirq_get(cq, tail_slot);
453 }
454 
455 static void
456 cirq_for(void *vcq, void (^iter)(void *elt))
457 {
458 	struct cirq *cq = vcq;
459 	for (unsigned int i = cq->tail_slot; i < cq->nslots; i++) {
460 		iter(cirq_get(cq, i));
461 	}
462 	for (unsigned int i = 0; i < cq->tail_slot; i++) {
463 		iter(cirq_get(cq, i));
464 	}
465 }
466 
467 #define HISTORY_LEN 5
468 
469 struct instval {
470 	uint64_t iv_instant_ns;
471 	uint64_t iv_val;
472 };
473 
474 struct cirq_instval {
475 	struct cirq cq;
476 	struct instval elts[HISTORY_LEN];
477 };
478 
479 struct cirq_u64 {
480 	struct cirq cq;
481 	uint64_t elts[HISTORY_LEN];
482 };
483 
484 struct cpu_oversample {
485 	struct cirq_instval timer_latencies;
486 	struct cirq_instval fire_latencies;
487 };
488 
489 static void
cpu_oversample_log(struct cpu_oversample * cpu,unsigned int cpuid)490 cpu_oversample_log(struct cpu_oversample *cpu, unsigned int cpuid)
491 {
492 	T_LOG("CPU %d timer latencies:", cpuid);
493 	__block int i = -HISTORY_LEN;
494 	cirq_for(&cpu->timer_latencies, ^(void *viv) {
495 		struct instval *iv = viv;
496 		T_LOG("\t%llu timer latency %d: %llu", iv->iv_instant_ns, i,
497 		    iv->iv_val);
498 		i++;
499 	});
500 
501 	T_LOG("CPU %d fire latencies:", cpuid);
502 	i = -HISTORY_LEN;
503 	cirq_for(&cpu->fire_latencies, ^(void *viv) {
504 		struct instval *iv = viv;
505 		T_LOG("\t%llu fire latency %d: %llu", iv->iv_instant_ns, i, iv->iv_val);
506 		i++;
507 	});
508 }
509 
510 T_DECL(kperf_timer_not_oversampling,
511     "ensure that time between fires is long enough")
512 {
513 	start_controlling_ktrace();
514 
515 	ktrace_session_t s = ktrace_session_create();
516 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(s, "ktrace_session_create");
517 	// Try not to perturb the system with more work.
518 	ktrace_set_collection_interval(s, 1000);
519 	__block uint64_t nfires = 0;
520 	__block uint64_t first_fire_ns = 0;
521 	__block uint64_t last_fire_ns = 0;
522 	__block unsigned int last_fire_cpuid = 0;
523 
524 	int ncpus = dt_ncpu();
525 	T_QUIET; T_ASSERT_GT(ncpus, 0, "should see positive number of CPUs");
526 
527 	struct cpu_oversample *per_cpu = calloc((unsigned int)ncpus,
528 			sizeof(per_cpu[0]));
529 	T_QUIET; T_WITH_ERRNO;
530 	T_ASSERT_NOTNULL(per_cpu, "allocated timer latency tracking");
531 	for (int i = 0; i < ncpus; i++) {
532 		per_cpu[i].timer_latencies.cq = CIRQ_INIT(struct instval, HISTORY_LEN);
533 		per_cpu[i].fire_latencies.cq = CIRQ_INIT(struct instval, HISTORY_LEN);
534 	}
535 
536 	__block bool in_stackshot = false;
537 	__block uint64_t last_stackshot_ns = 0;
538 
539 	// Stackshots are the primary source of interrupt latency on the system.
540 	ktrace_events_single(s, KDBG_EVENTID(DBG_BSD, DBG_BSD_EXCP_SC,
541 			SYS_stack_snapshot_with_config), ^(struct trace_point *tp) {
542 		bool start = tp->debugid & DBG_FUNC_START;
543 		uint64_t cur_ns = relns_from_abs(s, tp->timestamp);
544 		T_LOG("%llu: %s stackshot syscall from process %s",
545 				cur_ns, start ? "start" : "finish", tp->command);
546 		in_stackshot = start;
547 		if (!start) {
548 			last_stackshot_ns = cur_ns;
549 		}
550 	});
551 
552 	struct cirq_u64 *fire_times = calloc(1, sizeof(*fire_times));
553 	T_ASSERT_NOTNULL(fire_times, "allocated fire time tracking");
554 	fire_times->cq = CIRQ_INIT(uint64_t, HISTORY_LEN);
555 
556 	// Track the decrementer's latency values to find any unexpectedly long
557 	// interrupt latencies that could affect the firing cadence.
558 	ktrace_events_single(s, MACHDBG_CODE(DBG_MACH_EXCP_DECI, 0),
559 			^(struct trace_point *tp) {
560 		uint64_t cur_ns = relns_from_abs(s, tp->timestamp);
561 		uint64_t latency_ns = ns_from_abs(s, 0 - tp->arg1);
562 		struct instval *latency = cirq_push(&per_cpu[tp->cpuid].timer_latencies);
563 		latency->iv_instant_ns = cur_ns;
564 		latency->iv_val = latency_ns;
565 	});
566 
567 	ktrace_events_single(s, PERF_TMR_FIRE, ^(struct trace_point *tp) {
568 		T_QUIET; T_ASSERT_LT((int)tp->cpuid, ncpus,
569 				"timer fire should not occur on an IOP");
570 
571 		nfires++;
572 		uint64_t cur_ns = relns_from_abs(s, tp->timestamp);
573 		uint64_t *fire_ns = cirq_push(fire_times);
574 		*fire_ns = cur_ns;
575 
576 		struct cpu_oversample *cur_cpu = &per_cpu[tp->cpuid];
577 		struct instval *last_timer_latency = cirq_top(
578 				&cur_cpu->timer_latencies);
579 		uint64_t timer_latency_ns = last_timer_latency->iv_val;
580 
581 		if (first_fire_ns == 0) {
582 			first_fire_ns = cur_ns;
583 		} else {
584 			struct cpu_oversample *last_cpu = &per_cpu[last_fire_cpuid];
585 			struct instval *last_latency = cirq_top(&last_cpu->fire_latencies);
586 			uint64_t last_fire_latency_ns = last_latency->iv_val;
587 
588 			if (timer_latency_ns > TIMER_PERIOD_NS / 4) {
589 				T_LOG("%llu: long timer latency at fire: %llu", cur_ns,
590 						timer_latency_ns);
591 			}
592 
593 			// Long interrupt latencies will cause the timer to miss its fire
594 			// time and report a fire past when it should have, making the next
595 			// period too short.  Keep track of the latency as a leeway
596 			// adjustment for the subsequent fire.
597 			uint64_t fire_period_ns = cur_ns - last_fire_ns;
598 			uint64_t fire_period_adj_ns = fire_period_ns +
599 			    last_fire_latency_ns + timer_latency_ns;
600 			bool too_short = fire_period_adj_ns < FIRE_PERIOD_THRESHOLD_NS;
601 			if (too_short) {
602 				T_LOG("%llu: period of timer fire %llu is %llu + %llu + %llu = "
603 						"%llu < %llu",
604 						cur_ns, nfires, fire_period_ns, last_fire_latency_ns,
605 						timer_latency_ns, fire_period_adj_ns,
606 						FIRE_PERIOD_THRESHOLD_NS);
607 
608 				T_LOG("short profile timer fired on CPU %d", tp->cpuid);
609 				cpu_oversample_log(cur_cpu, tp->cpuid);
610 
611 				if (cur_cpu == last_cpu) {
612 					T_LOG("fired back-to-back on CPU %d", tp->cpuid);
613 				} else {
614 					T_LOG("previous profile timer fired on CPU %d",
615 							last_fire_cpuid);
616 					cpu_oversample_log(last_cpu, last_fire_cpuid);
617 				}
618 
619 				T_LOG("profile timer fires:");
620 				cirq_for(fire_times, ^(void *vu64) {
621 					T_LOG("\tfire: %llu", *(uint64_t *)vu64);
622 				});
623 				if (nfires < (unsigned int)ncpus) {
624 					T_LOG("ignoring timer fire %llu as context may be missing",
625 							nfires);
626 				} else {
627 					if (in_stackshot) {
628 						T_LOG("skipping assertion because stackshot is "
629 								"happening");
630 					} else if (last_stackshot_ns != 0 &&
631 							cur_ns > last_stackshot_ns &&
632 							cur_ns - last_stackshot_ns < TIMER_PERIOD_NS) {
633 						T_LOG("skipping assertion because stackshot happened "
634 								"%" PRIu64 "ns ago",
635 								cur_ns - last_stackshot_ns);
636 					} else {
637 						T_ASSERT_FAIL("profiling period is shorter than "
638 								"expected with no stackshot interference");
639 					}
640 				}
641 			}
642 
643 			struct instval *latency = cirq_push(&cur_cpu->fire_latencies);
644 			latency->iv_instant_ns = cur_ns;
645 			latency->iv_val = timer_latency_ns;
646 
647 			// Snapshot this timer fire's interrupt latency, so the next one
648 			// can make an adjustment to the period.
649 			last_fire_latency_ns = timer_latency_ns;
650 		}
651 		last_fire_ns = cur_ns;
652 		last_fire_cpuid = tp->cpuid;
653 
654 		if (nfires >= FIRES_THRESHOLD) {
655 			ktrace_end(s, 1);
656 		}
657 	});
658 
659 	configure_kperf_timer_samplers(TIMER_PERIOD_NS, KPERF_SAMPLER_TINFO);
660 
661 	ktrace_set_completion_handler(s, ^{
662 		double duration_secs = (double)(last_fire_ns - first_fire_ns) /
663 		    NSEC_PER_SEC;
664 		T_LOG("stopping trace after %.2f seconds", duration_secs);
665 
666 		T_PASS("saw %" PRIu64 " timer fires (%g fires/second) without "
667 			"oversampling", nfires, (double)nfires / (double)duration_secs);
668 
669 		T_END;
670 	});
671 
672 	start_tracing_with_timeout(s, 5);
673 
674 	// Get all CPUs out of idle.
675 	uint64_t *counts = kpc_counterbuf_alloc();
676 	(void)kpc_get_cpu_counters(true,KPC_CLASS_CONFIGURABLE_MASK, NULL, counts);
677 	free(counts);
678 
679 	dispatch_main();
680 }
681 
682 T_DECL(kperf_timer_stress, "repeatedly enable and disable timers")
683 {
684 	start_controlling_ktrace();
685 
686 	const int niters = 500;
687 	for (int i = 0; i < niters; i++) {
688 		configure_kperf_stacks_timer(-1, 1, true);
689 		T_QUIET;
690 		T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), "start kperf sampling");
691 		usleep(2000);
692 		kperf_reset();
693 	}
694 	T_LOG("configured kperf with a timer %d times", niters);
695 }
696 
697 #pragma mark - kdebug triggers
698 
699 #define KDEBUG_TRIGGER_TIMEOUT_NS (10 * NSEC_PER_SEC)
700 
701 #define NON_TRIGGER_CLASS    UINT32_C(0xfd)
702 #define NON_TRIGGER_SUBCLASS UINT32_C(0xff)
703 #define NON_TRIGGER_CODE     UINT32_C(0xff)
704 
705 #define NON_TRIGGER_EVENT \
706 	        (KDBG_EVENTID(NON_TRIGGER_CLASS, NON_TRIGGER_SUBCLASS, \
707 	        NON_TRIGGER_CODE))
708 
709 static void
expect_kdebug_trigger(const char * filter_desc,const uint32_t * debugids,unsigned int n_debugids)710 expect_kdebug_trigger(const char *filter_desc, const uint32_t *debugids,
711     unsigned int n_debugids)
712 {
713 	__block int missing_kernel_stacks = 0;
714 	__block int missing_user_stacks = 0;
715 	ktrace_session_t s;
716 	kperf_kdebug_filter_t filter;
717 
718 	s = ktrace_session_create();
719 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(s, "ktrace_session_create");
720 	ktrace_set_collection_interval(s, 100);
721 
722 	ktrace_events_single(s, PERF_STK_KHDR, ^(struct trace_point *tp) {
723 		missing_kernel_stacks--;
724 		T_LOG("saw kernel stack with %" PRIu64 " frames, flags = %#"
725 		PRIx64, tp->arg2, tp->arg1);
726 	});
727 	ktrace_events_single(s, PERF_STK_UHDR, ^(struct trace_point *tp) {
728 		missing_user_stacks--;
729 		T_LOG("saw user stack with %" PRIu64 " frames, flags = %#"
730 		PRIx64, tp->arg2, tp->arg1);
731 	});
732 
733 	for (unsigned int i = 0; i < n_debugids; i++) {
734 		ktrace_events_single(s, debugids[i], ^(struct trace_point *tp) {
735 			missing_kernel_stacks++;
736 			missing_user_stacks++;
737 			T_LOG("saw event with debugid 0x%" PRIx32, tp->debugid);
738 		});
739 	}
740 
741 	ktrace_events_single(s, NON_TRIGGER_EVENT,
742 	    ^(__unused struct trace_point *tp)
743 	{
744 		ktrace_end(s, 0);
745 	});
746 
747 	ktrace_set_completion_handler(s, ^{
748 		T_EXPECT_LE(missing_kernel_stacks, 0, NULL);
749 		T_EXPECT_LE(missing_user_stacks, 0, NULL);
750 
751 		ktrace_session_destroy(s);
752 		T_END;
753 	});
754 
755 	kperf_reset();
756 
757 	(void)kperf_action_count_set(1);
758 	T_ASSERT_POSIX_SUCCESS(kperf_action_samplers_set(1,
759 	    KPERF_SAMPLER_KSTACK | KPERF_SAMPLER_USTACK), NULL);
760 
761 	filter = kperf_kdebug_filter_create();
762 	T_ASSERT_NOTNULL(filter, NULL);
763 
764 	T_ASSERT_POSIX_SUCCESS(kperf_kdebug_action_set(1), NULL);
765 	T_ASSERT_POSIX_SUCCESS(kperf_kdebug_filter_add_desc(filter, filter_desc),
766 	    NULL);
767 	T_ASSERT_POSIX_SUCCESS(kperf_kdebug_filter_set(filter), NULL);
768 	kperf_kdebug_filter_destroy(filter);
769 
770 	T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), NULL);
771 
772 	T_ASSERT_POSIX_ZERO(ktrace_start(s, dispatch_get_main_queue()), NULL);
773 
774 	// Trace the triggering events.
775 
776 	for (unsigned int i = 0; i < n_debugids; i++) {
777 		T_ASSERT_POSIX_SUCCESS(kdebug_trace(debugids[i], 0, 0, 0, 0), NULL);
778 	}
779 
780 	T_ASSERT_POSIX_SUCCESS(kdebug_trace(NON_TRIGGER_EVENT, 0, 0, 0, 0), NULL);
781 
782 	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, KDEBUG_TRIGGER_TIMEOUT_NS),
783 	    dispatch_get_main_queue(), ^(void)
784 	{
785 		ktrace_end(s, 1);
786 	});
787 }
788 
789 #define TRIGGER_CLASS     UINT32_C(0xfe)
790 #define TRIGGER_CLASS_END UINT32_C(0xfd)
791 #define TRIGGER_SUBCLASS  UINT32_C(0xff)
792 #define TRIGGER_CODE      UINT32_C(0)
793 #define TRIGGER_DEBUGID \
794 	        (KDBG_EVENTID(TRIGGER_CLASS, TRIGGER_SUBCLASS, TRIGGER_CODE))
795 
796 T_DECL(kperf_kdebug_trigger_classes,
797     "test that kdebug trigger samples on classes")
798 {
799 	start_controlling_ktrace();
800 
801 	const uint32_t class_debugids[] = {
802 		KDBG_EVENTID(TRIGGER_CLASS, 1, 1),
803 		KDBG_EVENTID(TRIGGER_CLASS, 2, 1),
804 		KDBG_EVENTID(TRIGGER_CLASS_END, 1, 1) | DBG_FUNC_END,
805 		KDBG_EVENTID(TRIGGER_CLASS_END, 2, 1) | DBG_FUNC_END,
806 	};
807 
808 	expect_kdebug_trigger("C0xfe,C0xfdr", class_debugids,
809 	    sizeof(class_debugids) / sizeof(class_debugids[0]));
810 	dispatch_main();
811 }
812 
813 T_DECL(kperf_kdebug_trigger_subclasses,
814     "test that kdebug trigger samples on subclasses")
815 {
816 	start_controlling_ktrace();
817 
818 	const uint32_t subclass_debugids[] = {
819 		KDBG_EVENTID(TRIGGER_CLASS, TRIGGER_SUBCLASS, 0),
820 		KDBG_EVENTID(TRIGGER_CLASS, TRIGGER_SUBCLASS, 1),
821 		KDBG_EVENTID(TRIGGER_CLASS_END, TRIGGER_SUBCLASS, 0) | DBG_FUNC_END,
822 		KDBG_EVENTID(TRIGGER_CLASS_END, TRIGGER_SUBCLASS, 1) | DBG_FUNC_END
823 	};
824 
825 	expect_kdebug_trigger("S0xfeff,S0xfdffr", subclass_debugids,
826 	    sizeof(subclass_debugids) / sizeof(subclass_debugids[0]));
827 	dispatch_main();
828 }
829 
830 T_DECL(kperf_kdebug_trigger_debugids,
831     "test that kdebug trigger samples on debugids")
832 {
833 	start_controlling_ktrace();
834 
835 	const uint32_t debugids[] = {
836 		TRIGGER_DEBUGID
837 	};
838 
839 	expect_kdebug_trigger("D0xfeff0000", debugids,
840 	    sizeof(debugids) / sizeof(debugids[0]));
841 	dispatch_main();
842 }
843 
844 // TODO Set a single function specifier filter, expect not to trigger of all
845 // events from that class.
846 
847 static void
reset_kperf(void)848 reset_kperf(void)
849 {
850 	(void)kperf_reset();
851 	(void)sysctlbyname("kperf.debug_level", NULL, NULL, &(int){ 0 },
852 	    sizeof(int));
853 }
854 
855 T_DECL(kperf_kdbg_callstacks,
856     "test that the kdbg_callstacks samples on syscalls")
857 {
858 	start_controlling_ktrace();
859 
860 	ktrace_session_t s;
861 	__block bool saw_user_stack = false;
862 
863 	s = ktrace_session_create();
864 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(s, "ktrace_session_create");
865 	ktrace_set_collection_interval(s, 100);
866 
867 	// Make sure BSD events are traced in order to trigger samples on syscalls.
868 	ktrace_events_class(s, DBG_BSD, ^void (__unused struct trace_point *tp) {});
869 
870 	ktrace_events_single(s, PERF_STK_UHDR, ^(__unused struct trace_point *tp) {
871 		saw_user_stack = true;
872 		ktrace_end(s, 1);
873 	});
874 
875 	ktrace_set_completion_handler(s, ^{
876 		ktrace_session_destroy(s);
877 
878 		T_EXPECT_TRUE(saw_user_stack,
879 		"saw user stack after configuring kdbg_callstacks");
880 		T_END;
881 	});
882 
883 #pragma clang diagnostic push
884 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
885 	T_ASSERT_POSIX_SUCCESS(kperf_kdbg_callstacks_set(1), NULL);
886 #pragma clang diagnostic pop
887 	T_ATEND(reset_kperf);
888 
889 	T_ASSERT_POSIX_ZERO(ktrace_start(s, dispatch_get_main_queue()), NULL);
890 
891 	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC),
892 	    dispatch_get_main_queue(), ^(void) {
893 		ktrace_end(s, 1);
894 	});
895 
896 	dispatch_main();
897 }
898 
899 #pragma mark - PET
900 
901 #define STACKS_WAIT_DURATION_NS (3 * NSEC_PER_SEC)
902 
903 static void
904 expect_stacks_traced(void (^setup)(ktrace_session_t s), void (^complete)(void))
905 {
906 	ktrace_session_t s;
907 
908 	s = ktrace_session_create();
909 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(s, "ktrace_session_create");
910 	ktrace_set_collection_interval(s, 100);
911 	if (setup) {
912 		setup(s);
913 	}
914 
915 	__block unsigned int user_stacks = 0;
916 	__block unsigned int kernel_stacks = 0;
917 
918 	ktrace_events_single(s, PERF_STK_UHDR, ^(__unused struct trace_point *tp) {
919 		user_stacks++;
920 	});
921 	ktrace_events_single(s, PERF_STK_KHDR, ^(__unused struct trace_point *tp) {
922 		kernel_stacks++;
923 	});
924 
925 	ktrace_set_completion_handler(s, ^(void) {
926 		ktrace_session_destroy(s);
927 		T_EXPECT_GT(user_stacks, 0U, NULL);
928 		T_EXPECT_GT(kernel_stacks, 0U, NULL);
929 		complete();
930 	});
931 
932 	T_QUIET; T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), NULL);
933 
934 	T_ASSERT_POSIX_ZERO(ktrace_start(s, dispatch_get_main_queue()), NULL);
935 
936 	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, STACKS_WAIT_DURATION_NS),
937 	    dispatch_get_main_queue(), ^(void)
938 	{
939 		kperf_reset();
940 		ktrace_end(s, 0);
941 	});
942 }
943 
944 T_DECL(kperf_pet, "test that PET mode samples kernel and user stacks")
945 {
946 	start_controlling_ktrace();
947 
948 	configure_kperf_stacks_timer(-1, 10, false);
949 	T_ASSERT_POSIX_SUCCESS(kperf_timer_pet_set(0), NULL);
950 
951 	expect_stacks_traced(NULL, ^(void) {
952 		T_END;
953 	});
954 
955 	dispatch_main();
956 }
957 
958 T_DECL(kperf_lightweight_pet,
959     "test that lightweight PET mode samples kernel and user stacks",
960     T_META_ASROOT(true))
961 {
962 	start_controlling_ktrace();
963 
964 	int set = 1;
965 
966 	configure_kperf_stacks_timer(-1, 10, false);
967 	T_ASSERT_POSIX_SUCCESS(sysctlbyname("kperf.lightweight_pet", NULL, NULL,
968 	    &set, sizeof(set)), NULL);
969 	T_ASSERT_POSIX_SUCCESS(kperf_timer_pet_set(0), NULL);
970 
971 	__block uint64_t nfires = 0;
972 
973 	expect_stacks_traced(^(ktrace_session_t s) {
974 		ktrace_events_single(s, PERF_TMR_FIRE, ^(struct trace_point *tp) {
975 			nfires++;
976 			T_QUIET;
977 			T_ASSERT_EQ(tp->arg1, (uint64_t)0,
978 					"timer fire should have timer ID of 0");
979 			T_QUIET;
980 			T_ASSERT_EQ(tp->arg2, (uint64_t)1,
981 					"timer fire should have PET bit set");
982 		});
983 	}, ^(void) {
984 		T_ASSERT_GT(nfires, (uint64_t)0, "timer fired at least once");
985 		T_END;
986 	});
987 
988 	dispatch_main();
989 }
990 
991 T_DECL(kperf_pet_stress, "repeatedly enable and disable PET mode")
992 {
993 	start_controlling_ktrace();
994 
995 	const int niters = 500;
996 	for (int i = 0; i < niters; i++) {
997 		configure_kperf_stacks_timer(-1, 1, true);
998 		T_QUIET; T_ASSERT_POSIX_SUCCESS(kperf_timer_pet_set(0), NULL);
999 		T_QUIET;
1000 		T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), "start kperf sampling");
1001 		usleep(2000);
1002 		kperf_reset();
1003 	}
1004 
1005 	T_PASS("configured kperf PET %d times", niters);
1006 }
1007 
1008 #pragma mark - PMCs
1009 
1010 T_DECL(kperf_pmc_config_only,
1011     "shouldn't show PMC config events unless requested")
1012 {
1013 	start_controlling_ktrace();
1014 
1015 	__block bool saw_kpc_config = false;
1016 	__block bool saw_kpc_reg = false;
1017 
1018 	ktrace_session_t s = ktrace_session_create();
1019 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(s, "ktrace_session_create");
1020 	ktrace_set_collection_interval(s, 100);
1021 
1022 	ktrace_events_single(s, PERF_KPC_CONFIG,
1023 	    ^(__unused struct trace_point *tp) {
1024 		saw_kpc_config = true;
1025 	});
1026 	ktrace_events_single(s, PERF_KPC_REG,
1027 	    ^(__unused struct trace_point *tp) {
1028 		saw_kpc_reg = true;
1029 	});
1030 	ktrace_events_single(s, PERF_KPC_REG32,
1031 	    ^(__unused struct trace_point *tp) {
1032 		saw_kpc_reg = true;
1033 	});
1034 
1035 	ktrace_set_completion_handler(s, ^{
1036 		ktrace_session_destroy(s);
1037 		T_EXPECT_FALSE(saw_kpc_config,
1038 		"should see no KPC configs without sampler enabled");
1039 		T_EXPECT_FALSE(saw_kpc_reg,
1040 		"should see no KPC registers without sampler enabled");
1041 		T_END;
1042 	});
1043 
1044 	uint32_t nconfigs = kpc_get_config_count(KPC_CLASS_CONFIGURABLE_MASK);
1045 	uint64_t *config = calloc(nconfigs, sizeof(*config));
1046 	config[0] = 0x02;
1047 	int ret = kpc_set_config(KPC_CLASS_CONFIGURABLE_MASK, config);
1048 	T_ASSERT_POSIX_SUCCESS(ret, "configured kpc");
1049 	T_QUIET;
1050 	T_ASSERT_POSIX_SUCCESS(kpc_set_counting(KPC_CLASS_CONFIGURABLE_MASK),
1051 	    "kpc_set_counting");
1052 
1053 	(void)kperf_action_count_set(1);
1054 	T_ATEND(reset_kperf);
1055 	T_QUIET;
1056 	T_ASSERT_POSIX_SUCCESS(kperf_action_samplers_set(1, KPERF_SAMPLER_PMC_CPU),
1057 	    NULL);
1058 
1059 	(void)kperf_timer_count_set(1);
1060 	T_QUIET;
1061 	T_ASSERT_POSIX_SUCCESS(kperf_timer_period_set(0,
1062 	    kperf_ns_to_ticks(TIMER_PERIOD_NS)), NULL);
1063 	T_QUIET;
1064 	T_ASSERT_POSIX_SUCCESS(kperf_timer_action_set(0, 1), NULL);
1065 
1066 	T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), "start kperf sampling");
1067 
1068 	T_ASSERT_POSIX_ZERO(ktrace_start(s, dispatch_get_main_queue()), NULL);
1069 
1070 	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC),
1071 	    dispatch_get_main_queue(), ^(void) {
1072 		ktrace_end(s, 1);
1073 	});
1074 
1075 	dispatch_main();
1076 }
1077 
1078 static void
skip_if_monotonic_unsupported(void)1079 skip_if_monotonic_unsupported(void)
1080 {
1081 	int r;
1082 	int supported = 0;
1083 	size_t supported_size = sizeof(supported);
1084 
1085 	r = sysctlbyname("kern.monotonic.supported", &supported, &supported_size,
1086 	    NULL, 0);
1087 	if (r < 0) {
1088 		T_WITH_ERRNO;
1089 		T_SKIP("could not find \"kern.monotonic.supported\" sysctl");
1090 	}
1091 
1092 	if (!supported) {
1093 		T_SKIP("monotonic is not supported on this platform");
1094 	}
1095 }
1096 
1097 #define INSTRS_CYCLES_UPPER 500
1098 #define INSTRS_CYCLES_LOWER 50
1099 
1100 T_DECL(kperf_sample_instrs_cycles,
1101     "ensure instructions and cycles are sampled")
1102 {
1103 	T_SETUPBEGIN;
1104 
1105 	skip_if_monotonic_unsupported();
1106 	start_controlling_ktrace();
1107 
1108 	ktrace_session_t sess = ktrace_session_create();
1109 	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(sess, "ktrace_session_create");
1110 	ktrace_set_collection_interval(sess, 100);
1111 
1112 	__block uint64_t ninstrs_cycles = 0;
1113 	__block uint64_t nzeroes = 0;
1114 	ktrace_events_single(sess, PERF_INSTR_DATA,
1115 	    ^(__unused struct trace_point *tp) {
1116 		ninstrs_cycles++;
1117 		if (tp->arg1 == 0) {
1118 			T_LOG("%llx (%s)\n", tp->threadid, tp->command);
1119 			nzeroes++;
1120 		}
1121 		if (ninstrs_cycles >= INSTRS_CYCLES_UPPER) {
1122 			ktrace_end(sess, 1);
1123 		}
1124 	});
1125 
1126 	ktrace_set_collection_interval(sess, 200);
1127 
1128 	ktrace_set_completion_handler(sess, ^{
1129 		T_EXPECT_GE(ninstrs_cycles, (uint64_t)INSTRS_CYCLES_LOWER,
1130 		    "saw enough instructions and cycles events");
1131 		T_EXPECT_EQ(nzeroes, UINT64_C(0),
1132 		    "saw no events with 0 instructions");
1133 		T_END;
1134 	});
1135 
1136 	(void)kperf_action_count_set(1);
1137 	T_ATEND(reset_kperf);
1138 	T_QUIET;
1139 	T_ASSERT_POSIX_SUCCESS(kperf_action_samplers_set(1,
1140 	    KPERF_SAMPLER_TH_INSTRS_CYCLES), NULL);
1141 
1142 	(void)kperf_timer_count_set(1);
1143 	T_QUIET;
1144 	T_ASSERT_POSIX_SUCCESS(kperf_timer_period_set(0,
1145 	    kperf_ns_to_ticks(TIMER_PERIOD_NS)), NULL);
1146 	T_QUIET;
1147 	T_ASSERT_POSIX_SUCCESS(kperf_timer_action_set(0, 1), NULL);
1148 
1149 	T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), "start kperf sampling");
1150 
1151 	T_ASSERT_POSIX_ZERO(ktrace_start(sess, dispatch_get_main_queue()),
1152 	    NULL);
1153 
1154 	T_SETUPEND;
1155 
1156 	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC),
1157 	    dispatch_get_main_queue(), ^(void) {
1158 		ktrace_end(sess, 1);
1159 	});
1160 
1161 	dispatch_main();
1162 }
1163 
1164 #define UNCOMMON_EVENTID 0xfeedfac0
1165 #define LABEL "this_is_a_test_label_that_is_very_long_and_will_be_truncated" \
1166 		"_but_needs_some_more_length_for_good_measure"
1167 #define MAX_LABEL_LEN 64
1168 static_assert(sizeof(LABEL) > MAX_LABEL_LEN,
1169     "should be larger than the max length of a label");
1170 
1171 T_DECL(kperf_dispatch_labels, "ensure dispatch queue labels are sampled")
1172 {
1173 	T_SETUPBEGIN;
1174 	start_controlling_ktrace();
1175 	ktrace_session_t sess = ktrace_session_create();
1176 	ktrace_set_collection_interval(sess, 200);
1177 
1178 	/*
1179 	 * Expect to see the label that was sampled by kperf.
1180 	 */
1181 	__block uint64_t nlabels = 0;
1182 	char obs_label[MAX_LABEL_LEN + 1] = {};
1183 	char *obs_label_b = obs_label;
1184 	char exp_label[MAX_LABEL_LEN + 1] = {};
1185 	strlcpy(exp_label, LABEL, sizeof(exp_label));
1186 	char *exp_label_b = exp_label;
1187 
1188 	ktrace_events_single(sess, PERF_DISPLABEL, ^(struct trace_point *tp) {
1189 		nlabels++;
1190 		size_t argsize = ktrace_is_kernel_64_bit(sess) ? 8 : 4;
1191 		strncat(obs_label_b, (char *)&tp->arg1, argsize);
1192 		strncat(obs_label_b, (char *)&tp->arg2, argsize);
1193 		strncat(obs_label_b, (char *)&tp->arg3, argsize);
1194 		strncat(obs_label_b, (char *)&tp->arg4, argsize);
1195 		if (tp->debugid & DBG_FUNC_END) {
1196 			ktrace_end(sess, 1);
1197 		}
1198 	});
1199 	ktrace_events_single(sess, PERF_DISPSAMPLE, ^(struct trace_point *tp) {
1200 		if (tp->debugid & DBG_FUNC_END) {
1201 			T_LOG("ending sample event returned %d (%s)",
1202 			    (int)tp->arg1, strerror((int)tp->arg1));
1203 		}
1204 	});
1205 	ktrace_events_single(sess, UNCOMMON_EVENTID,
1206 	    ^(__unused struct trace_point *tp) {
1207 		T_LOG("saw triggering event");
1208 	});
1209 	ktrace_set_completion_handler(sess, ^{
1210 		T_EXPECT_GT(nlabels, 0ULL, "saw %" PRIu64
1211 		    " dispatch queue label events", nlabels);
1212 		T_EXPECT_EQ_STR(obs_label_b, exp_label_b, "label string is correct");
1213 		T_END;
1214 	});
1215 
1216 	/*
1217 	 * Set up kperf to log a dispatch queue label when an uncommon event ID
1218 	 * is traced.
1219 	 */
1220 	(void)sysctlbyname("kperf.debug_level", NULL, NULL, &(int){ 2 }, sizeof(int));
1221 	(void)kperf_action_count_set(1);
1222 	T_ATEND(reset_kperf);
1223 	T_QUIET;
1224 	T_ASSERT_POSIX_SUCCESS(kperf_action_samplers_set(1,
1225 	    KPERF_SAMPLER_TH_DISPATCH), NULL);
1226 	(void)kperf_kdebug_action_set(1);
1227 	kperf_kdebug_filter_t kdfilt = kperf_kdebug_filter_create();
1228 	T_QUIET;
1229 	T_ASSERT_NOTNULL(kdfilt, "create kdebug filter for kperf");
1230 	T_QUIET;
1231 	T_ASSERT_POSIX_SUCCESS(
1232 	    kperf_kdebug_filter_add_debugid(kdfilt, UNCOMMON_EVENTID),
1233 	    "add debugid to filter on");
1234 	T_QUIET;
1235 	T_ASSERT_POSIX_SUCCESS(
1236 	    kperf_kdebug_filter_set(kdfilt), "set filter for kperf");
1237 	T_ASSERT_POSIX_SUCCESS(kperf_sample_set(1), "start kperf sampling");
1238 
1239 	T_ASSERT_POSIX_ZERO(ktrace_start(sess, dispatch_get_main_queue()),
1240 	    NULL);
1241 
1242 	/*
1243 	 * Create the queue and emit the sampling event from it.
1244 	 */
1245 	dispatch_queue_t testq = dispatch_queue_create(LABEL, 0);
1246 	T_ASSERT_NOTNULL(testq, "created queue with label: " LABEL);
1247 	dispatch_async(testq, ^{
1248 		kdebug_trace(UNCOMMON_EVENTID, 0, 0, 0, 0);
1249 		sleep(10);
1250 	});
1251 
1252 	T_SETUPEND;
1253 
1254 	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC),
1255 	    dispatch_get_main_queue(), ^(void) {
1256 		ktrace_end(sess, 1);
1257 	});
1258 
1259 	dispatch_main();
1260 }
1261 
1262 T_HELPER_DECL(kperf_blessed_helper,
1263     "drop priviliges and attempt to configure kperf")
1264 {
1265 	drop_priv();
1266 	(void)kperf_action_count_set(1);
1267 	errno = 0;
1268 	int ret = kperf_lazy_wait_action_set(1);
1269 	int error = errno;
1270 	exit(ret != 0 ? (error == 0) ? EINVAL : error : 0);
1271 }
1272 
1273 static pid_t
spawn_bless_helper(void)1274 spawn_bless_helper(void)
1275 {
1276 	char test_path[MAXPATHLEN] = { 0 };
1277 	int ret = proc_pidpath(getpid(), test_path, MAXPATHLEN);
1278 	T_QUIET; T_ASSERT_POSIX_SUCCESS(ret, "query path for current process");
1279 	T_LOG("spawning helper tool at %s", test_path);
1280 	char *child_argv[] = { test_path, "-n", "kperf_blessed_helper", NULL };
1281 	pid_t child_pid = -1;
1282 	int error = dt_launch_tool(&child_pid, child_argv, true, NULL, NULL);
1283 	T_ASSERT_POSIX_ZERO(error, "spawned child with pid %d", child_pid);
1284 	T_QUIET; T_ASSERT_GT(child_pid, 0, "child pid is valid");
1285 	return child_pid;
1286 }
1287 
1288 static int
test_child_process(pid_t child_pid)1289 test_child_process(pid_t child_pid)
1290 {
1291 	int ret = kill(child_pid, SIGCONT);
1292 	T_ASSERT_POSIX_SUCCESS(ret, "continuing child process");
1293 	int status = 0;
1294 	ret = waitpid(child_pid, &status, 0);
1295 	T_ASSERT_POSIX_SUCCESS(ret, "waited on child process");
1296 	return status;
1297 }
1298 
1299 T_DECL(kperf_unblessed_refusal,
1300     "check that an unblessed child cannot access ktrace")
1301 {
1302 	T_SETUPBEGIN;
1303 	pid_t child_pid = spawn_bless_helper();
1304 	T_SETUPEND;
1305 	int status = test_child_process(child_pid);
1306 	int exit_status = WEXITSTATUS(status);
1307 	T_EXPECT_NE(exit_status, 0, "child failed to access ktrace with %d (%s)",
1308 		exit_status, exit_status == 0 ? "ok" : strerror(exit_status));
1309 }
1310 
1311 T_DECL(kperf_blessed_ownership, "check that a blessed child can access ktrace")
1312 {
1313 	T_LOG("parent pid is %d\n", getpid());
1314 	T_SETUPBEGIN;
1315 	pid_t child_pid = spawn_bless_helper();
1316 	T_SETUPEND;
1317 	int ret = kperf_bless_set(child_pid);
1318 	T_ASSERT_POSIX_SUCCESS(ret, "blessed child with pid %d", child_pid);
1319 	int status = test_child_process(child_pid);
1320 	int exit_status = WEXITSTATUS(status);
1321 	T_EXPECT_EQ(exit_status, 0, "child status was %d (%s)", exit_status,
1322 	    exit_status == 0 ? "ok" : strerror(exit_status));
1323 	ret = kperf_bless_set(-1);
1324 	T_ASSERT_POSIX_SUCCESS(ret, "removed blessing from child");
1325 }
1326