⬢ DragonFlyBSD Kernel Audit
DF-5568 / drift.c
← back to finding ↓ download raw
/*
 * DF-5568 — timer sanity check INSIDE the vkernel.
 *
 * Proves the one-shot systimer machinery still functions (no gross clock
 * drift, no lost sleeps) on both the stock (dead-CAS) and fixed kernels.
 * Bounding test: the dead while-loop in vktimer_intr_reload() is claimed
 * to be a correctness/dead-code defect, NOT a functional breakage — this
 * binary demonstrates the impact ceiling.
 *
 * build: cc -static -O2 -o drift drift.c
 * run  : ./drift   (inside the vkernel)
 * PASS : both ratios < 1.10 (10% slop for scheduling), TIMER_SANITY_OK
 */
#include <stdio.h>
#include <time.h>
#include <errno.h>

static unsigned long long now_ns(void)
{
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return (unsigned long long)ts.tv_sec * 1000000000ull +
	       (unsigned long long)ts.tv_nsec;
}

int main(void)
{
	struct timespec rq;
	unsigned long long t0, t1;
	int i;
	double exp_ms, act_ms, r10 = -1, r1 = -1;

	t0 = now_ns();
	for (i = 0; i < 200; i++) {
		rq.tv_sec = 0; rq.tv_nsec = 10 * 1000 * 1000;
		while (nanosleep(&rq, &rq) != 0) {
			if (errno != EINTR) {
				perror("nanosleep");
				return 2;
			}
		}
	}
	t1 = now_ns();
	exp_ms = 200 * 10.0;
	act_ms = (double)(t1 - t0) / 1e6;
	r10 = act_ms / exp_ms;
	printf("DRIFT10MS: expected %.1f ms actual %.1f ms ratio %.3f\n",
	       exp_ms, act_ms, r10);

	t0 = now_ns();
	for (i = 0; i < 1000; i++) {
		rq.tv_sec = 0; rq.tv_nsec = 1000 * 1000;
		while (nanosleep(&rq, &rq) != 0) {
			if (errno != EINTR) {
				perror("nanosleep");
				return 2;
			}
		}
	}
	t1 = now_ns();
	exp_ms = 1000 * 1.0;
	act_ms = (double)(t1 - t0) / 1e6;
	r1 = act_ms / exp_ms;
	printf("DRIFT1MS: expected %.1f ms actual %.1f ms ratio %.3f\n",
	       exp_ms, act_ms, r1);

	if (r10 < 1.10 && r1 < 1.10) {
		printf("TIMER_SANITY_OK\n");
		return 0;
	}
	printf("TIMER_SANITY_FAIL\n");
	return 1;
}