Skip to contentSkip to conversation

sched/deadline: bandwidth accounting fixes and selftests

PATCH In review Mathieu Desnoyers 4 participants 61 messages Dec 3 – Dec 4 Page 2 of 2

Subsystems (8)
lore
Share & tools
lore
#49 lore raw

PATCH v14 33/39 selftests/sched: Test parameter changes in deadline_bw_test

In reply to Mathieu Desnoyers

Add 25 cases to deadline_bw_test, for the fixes earlier in this series. The comment above each case gives its scenario. The cases form three groups:
- In 20 cases, a deadline task changes its parameters, or leaves the class and comes back with new ones. In params_swap_overload, two tasks pass a large runtime back and forth. This is Example 1 of Tang, Anderson and Abeni (RTNS 2021).
- In 4 cases, a constrained task leaves the class in its gap, and comes back with the same parameters. The gap is the time between its deadline and its next period.
- In params_return_full, a task of 60% leaves the class and comes back with the same parameters, before its 0-lag time. Its partition has no room for two tasks of 60%. The case fails without "sched/deadline:
Admit a returning task without the bandwidth it holds", and passes with it.

12 of the 20 cases fail on v7.4-rc2. Each one fails at the patch before the fix named here, and passes from that fix on:
- "sched/deadline: Cap the runtime left of a constrained task at dl_runtime": wake_constrained_new_params.
- "sched/deadline: Check the runtime of a task that comes back runnable": return_running_new_params.
- "sched/deadline: Keep the debt of a task across a change of parameters": change_running_new_params, constrained_gap_change_running, change_constrained_new_params, setattr_blocked_new_period, period_grown_untouched, deadline_widened_asleep, period_shrunk_throttled, period_shrunk_throttled_started, runtime_raised_waited and params_swap_overload.

The other 8 cases pass on v7.4-rc2 and with the whole series. They check that "sched/deadline: Keep the debt of a task across a change of parameters" starts the next period of a task neither too early nor too late. The 8 cases are setattr_blocked_reenter, deadline_grows_running, period_shrunk_running, period_grown_running, params_flip_no_gain, period_shrunk_no_burst, wake_after_deadline_shrunk and constrained_after_job. Three of them fail if dl_next_period() counts from period_start without the rules of that patch:
wake_after_deadline_shrunk, period_shrunk_no_burst and constrained_after_job.

The four reenter_*_in_gap cases pass on v7.4-rc2. Two patches of the first series make them fail:
- "sched/deadline: Reset the deadline and the runtime with the parameters": reenter_runnable_in_gap.
- "sched/deadline: Release the bandwidth of a task that leaves the class asleep": reenter_asleep_in_gap, reenter_asleep_late_in_gap and reenter_pi_blocked_in_gap.

reenter_asleep_late_in_gap passes again from "sched/deadline: Keep the deadline of a departed constrained task" on. The other three pass again from "sched/deadline: Count the 0-lag time from the next period" on.

The cases run in P, a one-CPU partition root. A task of a case can keep its bandwidth counted after it exits, until its 0-lag time. params_swap_overload leaves a debt that takes seconds to repay. random_mix runs right after it. It reads this_bw of P's CPU at its start, and checks that it is the same at its end. The debt was repaid in between, so random_mix failed in most runs. The harness now waits after each case, for up to 10s. It waits until the total_bw of P's CPU comes back down to its value before the case. It then waits, the same way, for this_bw of the three CPUs that random_mix checks. A task that a cpuset attach moves while it sleeps keeps its bandwidth in this_bw of its old CPU until it wakes up or dies.

In reenter_pi_blocked_in_gap, reenter_asleep_in_gap and reenter_asleep_late_in_gap, T leaves the class early in its second period. It keeps its bandwidth until its 0-lag time, before its third period. Each case waits for that third period before it returns. Else measured() can probe while T is still counted. The probe then sees no change only while T fits in the room left after the probe tasks.

With the whole series, every case of deadline_bw_test passes, PREEMPT_RT included. No kernel warning is logged.

---
 .../sched/deadline/deadline_bw_test.c         | 2223 ++++++++++++++++-
 1 file changed, 2163 insertions(+), 60 deletions(-)
tools/testing/selftests/sched/deadline/deadline_bw_test.c +2163 -60
index dbe0de739e47..58ec444cf1bb 100644
@@ -32,7 +32,9 @@
  *
  * The cases of p_cases[] run with P, a partition root of the last
  * housekeeping CPU. P is made anew for each case. Making it rebuilds the
- * accounting, which clears what an earlier case left.
+ * accounting, which clears what an earlier case leaked. A task that exits
+ * stays counted until its 0-lag time: run_p_cases() waits for that after
+ * each case.
  *
  * The cases of hp_cases[] run after them, without P. These are the
  * hotplug cases, and the cases with no_hp set, which take no CPU
@@ -54,6 +56,7 @@
 #include <fcntl.h>
 #include <limits.h>
 #include <pthread.h>
+#include <sys/klog.h>
 #include <sched.h>
 #include <semaphore.h>
 #include <signal.h>
@@ -280,6 +283,20 @@ static int set_deadline(pid_t tid, uint64_t runtime, uint64_t period)
 	return set_deadline_flags(tid, runtime, period, 0);
 }
 
+/* Make @tid a deadline task with a relative deadline shorter than @period. */
+static int set_constrained(pid_t tid, uint64_t runtime, uint64_t deadline, uint64_t period)
+{
+	struct dl_attr attr = {
+		.size = sizeof(attr),
+		.sched_policy = SCHED_DEADLINE,
+		.sched_runtime = runtime,
+		.sched_deadline = deadline,
+		.sched_period = period,
+	};
+
+	return syscall(SYS_sched_setattr, tid, &attr, 0) ? -errno : 0;
+}
+
 static int set_other(pid_t tid)
 {
 	struct dl_attr attr = { .size = sizeof(attr), .sched_policy = SCHED_OTHER };
@@ -877,7 +894,7 @@ static int pi_chain_two_owners(void)
 }
 
 /*
- * Run as the owner thread: take pi_lock, and sleep 400ms while holding
+ * Run as the owner thread. Take pi_lock, and sleep 400ms while holding
  * it. Return NULL, or 1 on an error.
  */
 static void *sleeping_owner(void *arg)
@@ -893,11 +910,11 @@ static void *sleeping_owner(void *arg)
 
 /*
  * A SCHED_OTHER owner takes pi_lock and sleeps 400ms while holding it.
- * The main thread then waits 20ms for the lock, 5 times. For each wait it
- * becomes a deadline task of 5ms every 50ms. Each wait boosts the
+ * The main thread then waits 20ms for the lock, @rounds times. For each
+ * wait it becomes a deadline task of 5ms every 50ms. Each wait boosts the
  * sleeping owner, and its timeout deboosts it. Every wait must time out.
  */
-static int pi_other_owner_asleep(void)
+static int pi_asleep(int rounds)
 {
 	pthread_t o;
 	int r, ret = KSFT_PASS;
@@ -914,9 +931,9 @@ static int pi_other_owner_asleep(void)
 	}
 	if (ret == KSFT_PASS)
 		sleep_ns(20 * NSEC_PER_MSEC);
-	for (r = 0; r < 5 && ret == KSFT_PASS; r++) {
+	for (r = 0; r < rounds && ret == KSFT_PASS; r++) {
 		if (wait_lock_for(20, 1)) {
-			ksft_print_msg("round %d of 5 failed\n", r + 1);
+			ksft_print_msg("round %d of %d failed\n", r + 1, rounds);
 			ret = KSFT_FAIL;
 		}
 	}
@@ -924,6 +941,11 @@ static int pi_other_owner_asleep(void)
 	return ret;
 }
 
+static int pi_other_owner_asleep(void)
+{
+	return pi_asleep(5);
+}
+
 /*
  * Run as the owner thread. Become a deadline task of 30ms every 100ms,
  * and take pi_lock. Hold it for 300ms, spinning 2ms and sleeping 5ms in
@@ -1455,6 +1477,82 @@ static int params_refused(void)
 	return ret;
 }
 
+static _Atomic uint64_t rt_t_slept;
+
+/*
+ * Run as T of params_return_full(). Become a deadline task of 60ms every
+ * 100ms. Sleep one period, so that the next wakeup starts a new period.
+ * Run 30ms of it, then sleep until t_exit is posted. Return NULL, or 1
+ * on an error.
+ */
+static void *runs_half_then_sleeps(void *arg)
+{
+	t_tid = gettid_();
+	if (set_deadline(0, 60 * NSEC_PER_MSEC, PERIOD)) {
+		t_state = -1;
+		return (void *)1;
+	}
+	sleep_ns(PERIOD);	/* a fresh period */
+	spin_ns(30 * NSEC_PER_MSEC);
+	rt_t_slept = now_ns();
+	t_state = 1;
+	sem_wait_sig(&t_exit);
+	return NULL;
+}
+
+/*
+ * A deadline task T of 60ms every 100ms runs 30ms of a fresh period, then
+ * sleeps with 30ms left. Its 0-lag time is 100 - 30 * 100 / 60 = 50ms
+ * into the period. Before then, the main thread switches T to
+ * SCHED_OTHER, then back to SCHED_DEADLINE with the same parameters. T
+ * still holds its 60% until its 0-lag time. P has no room for two tasks
+ * of 60%. The return must be admitted: its new bandwidth replaces the old
+ * one.
+ */
+static int params_return_full(void)
+{
+	int ret = KSFT_PASS, err;
+	uint64_t slept;
+	pthread_t t;
+
+	t_state = 0;
+	rt_t_slept = 0;
+	if (sem_init(&t_exit, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	if (pthread_create(&t, NULL, runs_half_then_sleeps, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		return KSFT_FAIL;
+	}
+	if (wait_for_step(5000, 100 * NSEC_PER_USEC, t_state) || t_state != 1 ||
+	    wait_for_step(5, 50 * NSEC_PER_USEC, proc_state_of(t_tid) == 'S')) {
+		ksft_print_msg("T was refused SCHED_DEADLINE, or never slept\n");
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	err = set_other(t_tid);
+	if (!err)
+		err = set_deadline(t_tid, 60 * NSEC_PER_MSEC, PERIOD);
+	slept = now_ns() - rt_t_slept;
+	if (slept > 15 * NSEC_PER_MSEC) {
+		/* Too late: the 0-lag time may have passed. */
+		ksft_print_msg("T switched back %llums after it slept\n",
+			       (unsigned long long)(slept / NSEC_PER_MSEC));
+		ret = KSFT_SKIP;
+	} else if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		ret = KSFT_FAIL;
+	}
+	if (ret == KSFT_PASS && probe(NULL) >= 6) {
+		ksft_print_msg("P has room for two tasks of 60%%\n");
+		ret = KSFT_SKIP;
+	}
+out:
+	stop_sleeper(t);
+	return ret;
+}
+
 /*
  * A SCHED_OTHER task with a slice of 40ms asks for SCHED_DEADLINE with
  * SCHED_FLAG_KEEP_PARAMS. That changes the class, so it must be refused
@@ -1560,7 +1658,7 @@ static int params_keep_boosted(void)
 
 	if (pi_init())
 		return KSFT_SKIP;
-	if (pthread_create(&o, NULL, sleeping_owner, (void *)0L)) {
+	if (pthread_create(&o, NULL, sleeping_owner, NULL)) {
 		ksft_print_msg("the owner thread could not start\n");
 		return KSFT_FAIL;
 	}
@@ -1604,7 +1702,7 @@ static int boosted_owner_policy(void)
 
 	if (pi_init())
 		return KSFT_SKIP;
-	if (pthread_create(&o, NULL, sleeping_owner, (void *)0L)) {
+	if (pthread_create(&o, NULL, sleeping_owner, NULL)) {
 		ksft_print_msg("the owner thread could not start\n");
 		return KSFT_FAIL;
 	}
@@ -1691,8 +1789,9 @@ static void *donor_waiter(void *arg)
 }
 
 /*
- * The owner O starts as SCHED_OTHER. The donor D is the waiter that
- * boosts it: a deadline task of 40ms every 100ms.
+ * A deboost ends the period of the donor. The owner O starts as
+ * SCHED_OTHER. The donor D is the waiter that boosts it: a deadline task
+ * of 40ms every 100ms.
  * 1. O takes pi_lock and spins.
  * 2. D blocks on pi_lock. This boosts O, which then runs on D's runtime.
  * 3. O spins 5ms more and unlocks. The unlock deboosts O.
@@ -1812,10 +1911,10 @@ static void *refill_donor(void *arg)
 }
 
 /*
- * Run as the owner O of deboost_keeps_own_runtime(). @arg is the CPU
- * time, in ms, that O spins with the lock once it is boosted. Store the
- * runtime O has left after the unlock in refill_owner_left. Return NULL,
- * 1 on an error, or 2 if the donor did not block on the lock within 1s.
+ * Run as the owner O of deboost_keeps_own_runtime(). Spin 1ms with the
+ * lock once boosted. Store in refill_owner_left the runtime O has left
+ * after the unlock. Return NULL, 1 on an error, or 2 if the donor did not
+ * block on the lock within 1s.
  */
 static void *refill_owner(void *arg)
 {
@@ -1841,7 +1940,7 @@ static void *refill_owner(void *arg)
 			return (void *)2;
 		}
 	}
-	spin_ns((long)arg * NSEC_PER_MSEC);
+	spin_ns(NSEC_PER_MSEC);
 	drop_pi_lock();
 	refill_owner_left = dl_runtime_left(owner_tid);
 	if (set_other(0))
@@ -1850,8 +1949,8 @@ static void *refill_owner(void *arg)
 }
 
 /*
- * Run a case on the runtime that a deadline owner has after its boost.
- * O and D share the CPU of P.
+ * A deadline owner keeps its own runtime after a boost. O and D share
+ * the CPU of P.
  *
  *   owner O: 5ms every 100ms             donor D: 2ms every 10ms
  *
@@ -1867,11 +1966,10 @@ static void *refill_owner(void *arg)
  *                                        takes pi_lock, unlocks
  *   reads its dl.runtime
  *
- * A boosted task that runs out of runtime is not throttled. Its runtime
- * is refilled from the parameters of its donor. Here O has used about 3ms
- * of its own 5ms at the unlock, and was never refilled. It must keep what
- * it has left. A new period would hand it a full runtime at every
- * contended unlock. The case fails if O has 4ms or more.
+ * O has used about 3ms of its own 5ms at the unlock, and was never
+ * refilled from D. It must keep what it has left. A new period would
+ * hand it a full runtime at every contended unlock. The case fails if O
+ * has 4ms or more.
  */
 static int deboost_keeps_own_runtime(void)
 {
@@ -1900,7 +1998,7 @@ static int deboost_keeps_own_runtime(void)
 		join(d);
 		return KSFT_FAIL;
 	}
-	if (pthread_create(&o, NULL, refill_owner, (void *)1L)) {
+	if (pthread_create(&o, NULL, refill_owner, NULL)) {
 		ksft_print_msg("the owner thread could not start\n");
 		sem_post(&owner_go);
 		join(d);
@@ -1940,17 +2038,27 @@ static _Atomic pid_t ret_tid;
 static atomic_int ret_first_period_ms;
 
 /*
- * Run as the thread of return_asleep_new_params(). Become a deadline task
- * of 50ms every 100ms and run 20ms. 30ms of runtime are left, and the
- * 0-lag time is about 20ms ahead. Then sleep. The main thread switches
- * the thread to SCHED_OTHER and back, with 10ms every 100ms. Then spin
- * for 100ms, and store the CPU time used, in ms, in ret_first_period_ms.
- * Return NULL, or 1 on an error.
+ * Run as the thread of the return cases. Become a deadline task of 50ms
+ * every 100ms and run 20ms. 30ms of runtime are left, and the 0-lag time
+ * is about 20ms ahead. Then change to new parameters, as @arg says:
+ * - 0: the thread switches itself to SCHED_OTHER and back to
+ *   SCHED_DEADLINE, while it runs.
+ * - 1: the thread sleeps. The main thread switches it to SCHED_OTHER and
+ *   back.
+ * - 2: the thread changes its own parameters while it runs. It stays in
+ *   SCHED_DEADLINE.
+ * - 3: as 2, to a constrained deadline: 8ms in 20ms, every 100ms.
+ * - 4: the thread sleeps. The main thread changes it to 8ms in 20ms,
+ *   every 100ms.
+ * The new parameters are 10ms every 100ms, except in modes 3 and 4.
+ * Then spin for 100ms, and store the CPU time used, in ms, in
+ * ret_first_period_ms. Return NULL, or 1 on an error.
  */
 static void *returner(void *arg)
 {
+	long mode = (long)arg;
 	uint64_t t0, cpu0;
-	int err;
+	int err = 0;
 
 	ret_tid = gettid_();
 	err = set_deadline(0, 50 * NSEC_PER_MSEC, PERIOD);
@@ -1959,8 +2067,20 @@ static void *returner(void *arg)
 		return (void *)1;
 	}
 	spin_ns(20 * NSEC_PER_MSEC);
-	sem_post(&ret_ready);
-	sem_wait_sig(&ret_go);
+	if (mode == 1 || mode == 4) {
+		sem_post(&ret_ready);
+		sem_wait_sig(&ret_go);
+	} else if (mode == 3) {
+		err = set_constrained(0, 8 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	} else {
+		err = mode ? 0 : set_other(0);
+		if (!err)
+			err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	}
+	if (err) {
+		ksft_print_msg("the task could not change: %s\n", strerror(-err));
+		return (void *)1;
+	}
 	t0 = now_ns();
 	cpu0 = thread_time_ns();
 	while (now_ns() - t0 < PERIOD)
@@ -1970,16 +2090,15 @@ static void *returner(void *arg)
 }
 
 /*
- * A task leaves SCHED_DEADLINE while it sleeps, and comes back at once
- * with a smaller runtime. Its 0-lag time is ahead, so it keeps its
- * deadline and the runtime it has left. returner() runs the task. It must
- * get about 10ms of CPU time in the 100ms after the change: its new
- * runtime, not the 30ms left from the old one. The case fails above 20ms.
+ * Run a return case: returner() with @mode as its argument. The thread
+ * must get about 10ms of CPU time in the 100ms after the change, 8ms in
+ * modes 3 and 4. That is its new runtime, not the 30ms left from the old
+ * one. The case fails above 20ms.
  */
-static int return_asleep_new_params(void)
+static int return_case(long mode)
 {
-	void *t_ret;
 	int err, ret = KSFT_PASS;
+	void *t_ret = NULL;
 	pthread_t t;
 
 	if (sem_init(&ret_ready, 0, 0) || sem_init(&ret_go, 0, 0)) {
@@ -1987,27 +2106,33 @@ static int return_asleep_new_params(void)
 		return KSFT_FAIL;
 	}
 	ret_first_period_ms = -1;
-	if (pthread_create(&t, NULL, returner, NULL)) {
+	if (pthread_create(&t, NULL, returner, (void *)mode)) {
 		ksft_print_msg("the task thread could not start\n");
 		return KSFT_FAIL;
 	}
-	if (sem_wait_for(&ret_ready, 5000)) {
-		/* The thread may get there late. Let it end. */
+	if (mode == 1 || mode == 4) {
+		if (sem_wait_for(&ret_ready, 5000)) {
+			/* The thread may get there late. Let it end. */
+			sem_post(&ret_go);
+			join(t);
+			return KSFT_FAIL;	/* the task said why */
+		}
+		/* Before its 0-lag time, about 20ms ahead */
+		err = wait_for(10, proc_state_of(ret_tid) == 'S') ? -EAGAIN : 0;
+		if (!err && mode == 1)
+			err = set_other(ret_tid);
+		if (!err && mode == 1)
+			err = set_deadline(ret_tid, 10 * NSEC_PER_MSEC, PERIOD);
+		if (!err && mode == 4)
+			err = set_constrained(ret_tid, 8 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+					      PERIOD);
 		sem_post(&ret_go);
-		join(t);
-		return KSFT_FAIL;	/* the task said why */
-	}
-	/* Before its 0-lag time, about 20ms ahead */
-	err = wait_for(10, proc_state_of(ret_tid) == 'S') ? -EAGAIN : 0;
-	if (!err)
-		err = set_other(ret_tid);
-	if (!err)
-		err = set_deadline(ret_tid, 10 * NSEC_PER_MSEC, PERIOD);
-	sem_post(&ret_go);
-	if (err) {
-		ksft_print_msg("the task could not change asleep: %s\n", strerror(-err));
-		join(t);
-		return KSFT_FAIL;
+		if (err) {
+			ksft_print_msg("the task could not change asleep: %s\n",
+				       strerror(-err));
+			join(t);
+			return KSFT_FAIL;
+		}
 	}
 	err = pthread_join(t, &t_ret);
 	if (err) {
@@ -2025,11 +2150,1649 @@ static int return_asleep_new_params(void)
 	return ret;
 }
 
+/*
+ * A running task leaves SCHED_DEADLINE and comes back at once with a
+ * smaller runtime. Its 0-lag time is ahead, so it keeps its deadline and
+ * the runtime it has left. It must not run on more than the new runtime.
+ */
+static int return_running_new_params(void)
+{
+	return return_case(0);
+}
+
+/* The same, for a task that leaves and comes back while it sleeps. */
+static int return_asleep_new_params(void)
+{
+	return return_case(1);
+}
+
+/* The same, for a task that changes its parameters within the class. */
+static int change_running_new_params(void)
+{
+	return return_case(2);
+}
+
+/*
+ * A running task of 50ms every 100ms has 30ms left. It changes itself to
+ * 8ms in 20ms, every 100ms. Its deadline stays 80ms ahead, further than
+ * the new 20ms. The check of the runtime left uses the new density over
+ * those 80ms. That allows 32ms, so the check keeps the 30ms. The task
+ * must keep no more than its new 8ms.
+ */
+static int change_constrained_new_params(void)
+{
+	return return_case(3);
+}
+
+/*
+ * The same, for a task that the main thread changes while it sleeps. The
+ * check is at its wakeup.
+ */
+static int wake_constrained_new_params(void)
+{
+	return return_case(4);
+}
+
+static sem_t shrink_ready;
+static _Atomic pid_t shrink_tid;
+static _Atomic unsigned long long shrink_t0;
+static _Atomic long long shrink_back_ms;
+
+/*
+ * Run as T of wake_after_deadline_shrunk(). Its comment has the steps.
+ * Store in shrink_back_ms the time at which T runs after its sleep.
+ * Return NULL, or 1 on an error.
+ */
+static void *shrink_t(void *arg)
+{
+	struct timespec ts;
+	uint64_t t0, end;
+	int err;
+
+	shrink_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	shrink_t0 = t0;
+	sem_post(&shrink_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(NSEC_PER_MSEC);
+	end = t0 + 110 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	shrink_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Shorten the relative deadline of a task asleep past its deadline:
+ * 1. T makes itself a deadline task of 10ms every 100ms, at 0ms. Its
+ *    deadline is 100ms. It runs 1ms, and sleeps until 110ms.
+ * 2. At 105ms, the main thread changes T to 10ms in 20ms, every 100ms.
+ * 3. T wakes up at 110ms.
+ *
+ * T's job ran. It counts as a job of the new parameters with the same
+ * deadline, released at 100 - 20 = 80ms. So T's next period starts at
+ * 80 + 100 = 180ms, and T runs then. A new period at the wakeup would
+ * start only 30ms after the release of the job that ran. That is less
+ * than a period of the new parameters. The case fails if T runs before
+ * 170ms or at 200ms or later.
+ */
+static int wake_after_deadline_shrunk(void)
+{
+	void *t_ret = NULL;
+	int err, ret = KSFT_FAIL;
+	uint64_t at;
+	pthread_t t;
+
+	if (sem_init(&shrink_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	shrink_back_ms = -1;
+	if (pthread_create(&t, NULL, shrink_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&shrink_ready, 5000)) {
+		join(t);
+		goto out;
+	}
+	at = shrink_t0 + 105 * NSEC_PER_MSEC;
+	while (now_ns() < at)
+		sleep_ns(NSEC_PER_MSEC);
+	if (proc_state_of(shrink_tid) != 'S') {
+		ksft_print_msg("T is not asleep at 105ms\n");
+		join(t);
+		goto out;
+	}
+	err = set_constrained(shrink_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+			      PERIOD);
+	if (err) {
+		ksft_print_msg("T could not change asleep: %s\n", strerror(-err));
+		join(t);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || shrink_back_ms < 0)
+		goto out;	/* T said why */
+	if (shrink_back_ms < 170 || shrink_back_ms >= 200) {
+		ksft_print_msg("T ran again at %lld ms, not at 180\n",
+			       (long long)shrink_back_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&shrink_ready);
+	return ret;
+}
+
+static sem_t widen_ready;
+static _Atomic pid_t widen_tid;
+static _Atomic unsigned long long widen_t0;
+static _Atomic long long widen_used_us;
+
+/*
+ * Run as T of deadline_widened_asleep(). Its comment has the steps.
+ * Store in widen_used_us the CPU time that T gets from 30ms to 95ms.
+ * Return NULL, or 1 on an error.
+ */
+static void *widen_t(void *arg)
+{
+	struct timespec ts;
+	uint64_t t0, end, cpu0;
+	int err;
+
+	widen_tid = gettid_();
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	widen_t0 = t0;
+	sem_post(&widen_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(8 * NSEC_PER_MSEC);
+	end = t0 + 30 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	cpu0 = thread_time_ns();
+	while (now_ns() < t0 + 95 * NSEC_PER_MSEC)
+		;
+	widen_used_us = (thread_time_ns() - cpu0) / NSEC_PER_USEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Widen the relative deadline of a task asleep in its period:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 100ms, at 0ms. It
+ *    spins 8ms and sleeps until 30ms.
+ * 2. At 25ms, the main thread changes T to 10ms every 100ms. T's deadline
+ *    is now 100ms. It has 2ms of runtime left.
+ * 3. T wakes up at 30ms and spins until 95ms.
+ *
+ * T must get about its 2ms left before 100ms. If its deadline stayed at
+ * 20ms, it would have passed at the wakeup. T would then get a new period
+ * of 10ms. The case fails if T gets 5ms of CPU time or more.
+ */
+static int deadline_widened_asleep(void)
+{
+	void *t_ret = NULL;
+	int err, ret = KSFT_FAIL;
+	uint64_t at;
+	pthread_t t;
+
+	if (sem_init(&widen_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	widen_used_us = -1;
+	if (pthread_create(&t, NULL, widen_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&widen_ready, 5000)) {
+		join(t);
+		goto out;
+	}
+	at = widen_t0 + 25 * NSEC_PER_MSEC;
+	while (now_ns() < at)
+		sleep_ns(NSEC_PER_MSEC);
+	if (proc_state_of(widen_tid) != 'S') {
+		ksft_print_msg("T is not asleep at 25ms\n");
+		join(t);
+		goto out;
+	}
+	err = set_deadline(widen_tid, 10 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("T could not change asleep: %s\n", strerror(-err));
+		join(t);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || widen_used_us < 0)
+		goto out;	/* T said why */
+	if (widen_used_us >= 5000) {
+		ksft_print_msg("T got %lld us before its deadline, with 2ms left\n",
+			       (long long)widen_used_us);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&widen_ready);
+	return ret;
+}
+
+/*
+ * The kernel prints this when a refill finds a deadline long passed. It
+ * prints it once per boot, so a case can see it only if no earlier test
+ * caused it.
+ */
+#define DL_LAG_MSG	"sched: DL replenish lagged too much"
+
+/*
+ * Return 1 if the kernel log holds @s, 0 if it does not, or -1 if it
+ * cannot be read.
+ */
+static int klog_has(const char *s)
+{
+	int len = klogctl(10, NULL, 0);		/* SYSLOG_ACTION_SIZE_BUFFER */
+	char *buf;
+	int n, ret;
+
+	if (len <= 0)
+		return -1;
+	buf = malloc(len + 1);
+	if (!buf)
+		return -1;
+	n = klogctl(3, buf, len);		/* SYSLOG_ACTION_READ_ALL */
+	ret = -1;
+	if (n >= 0) {
+		buf[n] = '\0';
+		ret = !!strstr(buf, s);
+	}
+	free(buf);
+	return ret;
+}
+
+static sem_t shorten_ready;
+static _Atomic pid_t shorten_tid;
+static _Atomic unsigned long long shorten_t0;
+static _Atomic long long shorten_back_ms;
+
+/*
+ * Run as T of period_shrunk_throttled(). Its comment has the steps. Store
+ * in shorten_back_ms the time at which T runs after its yield. Return
+ * NULL, or 1 on an error.
+ */
+static void *shorten_t(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	shorten_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	shorten_t0 = t0;
+	sem_post(&shorten_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(8 * NSEC_PER_MSEC);
+	sched_yield();
+	shorten_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Shorten the period of a task throttled until its next period:
+ * 1. T becomes a deadline task of 10ms every 100ms, at 0ms. It runs 8ms
+ *    and yields. Its replenishment timer is armed at 100ms.
+ * 2. At @at_ms, the main thread changes T to 10ms every @period_ms.
+ *
+ * T ran ahead of its share: its 0-lag time is at 80ms. The change keeps
+ * that debt, and repays it at the new bandwidth. T's next period starts
+ * once it is repaid. The timer must be armed again there. T must run
+ * again at @back_ms: the case fails 5ms before it, or 30ms after it. A
+ * refill at 100ms would also find a period that ended before, and print
+ * "sched: DL replenish lagged too much". The case fails if that message
+ * is logged. It skips if the message was logged before: the kernel prints
+ * it once.
+ */
+static int shorten_case(int at_ms, int period_ms, int back_ms)
+{
+	void *t_ret = NULL;
+	int err, had, ret = KSFT_FAIL;
+	uint64_t at;
+	pthread_t t;
+
+	had = klog_has(DL_LAG_MSG);
+	if (had) {
+		ksft_print_msg(had < 0 ? "the kernel log cannot be read\n" :
+			       "the lag message was logged before this case\n");
+		return KSFT_SKIP;
+	}
+	if (sem_init(&shorten_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	shorten_back_ms = -1;
+	if (pthread_create(&t, NULL, shorten_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&shorten_ready, 5000)) {
+		join(t);
+		goto out;
+	}
+	at = shorten_t0 + at_ms * NSEC_PER_MSEC;
+	while (now_ns() < at)
+		sleep_ns(NSEC_PER_MSEC);
+	err = set_deadline(shorten_tid, 10 * NSEC_PER_MSEC, period_ms * NSEC_PER_MSEC);
+	if (err) {
+		ksft_print_msg("T could not change throttled: %s\n", strerror(-err));
+		join(t);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || shorten_back_ms < 0)
+		goto out;	/* T said why */
+	if (shorten_back_ms < back_ms - 5 || shorten_back_ms >= back_ms + 30) {
+		ksft_print_msg("T ran again at %lld ms, not at its next period at %d\n",
+			       (long long)shorten_back_ms, back_ms);
+		goto out;
+	}
+	if (klog_has(DL_LAG_MSG) == 1) {
+		ksft_print_msg("the refill logged \"%s\"\n", DL_LAG_MSG);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&shorten_ready);
+	return ret;
+}
+
+/*
+ * Shorten the period of a throttled task: shorten_case() with a change at
+ * 30ms to a period of 50ms. T then owes 5ms, repaid at 20% in 25ms. T
+ * must run again at 55ms.
+ */
+static int period_shrunk_throttled(void)
+{
+	return shorten_case(30, 50, 55);
+}
+
+/*
+ * Shorten the period of a throttled task, later in its period:
+ * shorten_case() with a change at 60ms to a period of 20ms. T then owes
+ * 2ms, repaid at 50% in 4ms. T must run again at 64ms.
+ */
+static int period_shrunk_throttled_started(void)
+{
+	return shorten_case(60, 20, 64);
+}
+
+/* The kinds of period_rule_case() */
+enum { PR_SHRUNK, PR_GROWN, PR_UNTOUCHED, PR_RAISED };
+
+static sem_t pr_h_ready, pr_h_go;
+static atomic_int pr_h_err;
+static int pr_kind;
+static _Atomic long long pr_pre_cpu_ms, pr_mark_ms, pr_done_ms;
+
+/*
+ * Run as H of period_rule_case(). Become a deadline task with a deadline
+ * earlier than T's, and wait for pr_h_go. Then keep the CPU: 5ms with
+ * PR_UNTOUCHED, 60ms with PR_RAISED. Return NULL, or 1 on an error.
+ */
+static void *pr_h(void *arg)
+{
+	int err;
+
+	if (pr_kind == PR_UNTOUCHED)
+		err = set_constrained(0, 6 * NSEC_PER_MSEC, 10 * NSEC_PER_MSEC, PERIOD);
+	else
+		err = set_constrained(0, 62 * NSEC_PER_MSEC, 65 * NSEC_PER_MSEC, PERIOD);
+	pr_h_err = err;
+	sem_post(&pr_h_ready);
+	if (err) {
+		ksft_print_msg("H refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&pr_h_go);
+	spin_ns((pr_kind == PR_UNTOUCHED ? 5 : 60) * NSEC_PER_MSEC);
+	if (set_other(0))
+		ksft_print_msg("H cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as T of period_rule_case(). The comments of the cases have the
+ * steps. Store the times of T's marks in pr_mark_ms and pr_done_ms, and
+ * the CPU time T used before its change in pr_pre_cpu_ms. Return NULL, or
+ * 1 on an error.
+ */
+static void *pr_t(void *arg)
+{
+	uint64_t ms = NSEC_PER_MSEC, t0, c0;
+	int err;
+
+	if (pr_kind == PR_RAISED)
+		err = set_deadline(0, 10 * ms, PERIOD);
+	else
+		err = set_constrained(0, 10 * ms, 20 * ms,
+				      pr_kind == PR_SHRUNK ? PERIOD : PERIOD / 2);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		sem_post(&pr_h_go);
+		return (void *)1;
+	}
+	t0 = now_ns();
+	c0 = thread_time_ns();
+	switch (pr_kind) {
+	case PR_SHRUNK:
+	case PR_GROWN:
+		spin_ns(3 * ms);
+		break;
+	case PR_UNTOUCHED:
+		/* H preempts T here, for 5ms. */
+		sem_post(&pr_h_go);
+		while (now_ns() - t0 < 4 * ms)
+			;
+		break;
+	case PR_RAISED:
+		spin_ns(2 * ms);
+		/* H preempts T here, for 60ms. */
+		sem_post(&pr_h_go);
+		while (now_ns() - t0 < 55 * ms)
+			;
+		break;
+	}
+	pr_pre_cpu_ms = (thread_time_ns() - c0) / ms;
+	if (pr_kind == PR_RAISED)
+		err = set_deadline(0, 15 * ms, PERIOD);
+	else
+		err = set_constrained(0, 10 * ms, 20 * ms,
+				      pr_kind == PR_SHRUNK ? PERIOD / 2 : PERIOD);
+	if (err) {
+		ksft_print_msg("T could not change: %s\n", strerror(-err));
+		set_other(0);
+		return (void *)1;
+	}
+	switch (pr_kind) {
+	case PR_SHRUNK:
+		spin_ns(9 * ms);
+		break;
+	case PR_GROWN:
+		spin_ns(4 * ms);
+		pr_mark_ms = (now_ns() - t0) / ms;
+		spin_ns(5 * ms);
+		break;
+	case PR_UNTOUCHED:
+		spin_ns(9 * ms);
+		break;
+	case PR_RAISED:
+		spin_ns(12 * ms);
+		break;
+	}
+	pr_done_ms = (now_ns() - t0) / ms;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run a case where T changes its own parameters while it runs. P has one
+ * CPU. With PR_UNTOUCHED and PR_RAISED, a deadline task H first keeps T
+ * off the CPU: H has the earlier deadline. So T has more runtime left than
+ * a wakeup at that time would give it. H sleeps more than its period
+ * before T wakes it: its wakeup then starts a new period.
+ */
+static int period_rule_case(int kind)
+{
+	int with_h = kind == PR_UNTOUCHED || kind == PR_RAISED;
+	void *h_ret = NULL, *t_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t h, t;
+
+	if (sem_init(&pr_h_ready, 0, 0) || sem_init(&pr_h_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	pr_kind = kind;
+	pr_pre_cpu_ms = -1;
+	pr_mark_ms = -1;
+	pr_done_ms = -1;
+	if (with_h) {
+		if (pthread_create(&h, NULL, pr_h, NULL)) {
+			ksft_print_msg("the H thread could not start\n");
+			goto out;
+		}
+		if (sem_wait_for(&pr_h_ready, 5000) || pr_h_err) {
+			sem_post(&pr_h_go);
+			join(h);
+			goto out;	/* H said why */
+		}
+		sleep_ns(PERIOD + 10 * NSEC_PER_MSEC);
+	}
+	if (pthread_create(&t, NULL, pr_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		t_ret = (void *)1;
+	} else {
+		pthread_join(t, &t_ret);
+	}
+	if (with_h) {
+		sem_post(&pr_h_go);	/* if T never woke H */
+		pthread_join(h, &h_ret);
+	}
+	if (t_ret || h_ret || pr_done_ms < 0)
+		goto out;	/* the thread said why */
+	switch (kind) {
+	case PR_SHRUNK:
+		if (pr_done_ms < 45 || pr_done_ms >= 80) {
+			ksft_print_msg("T ended at %lld ms: its next period is at 50\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	case PR_GROWN:
+		if (pr_mark_ms >= 30) {
+			ksft_print_msg("T used 7ms of its runtime by %lld ms\n",
+				       (long long)pr_mark_ms);
+			goto out;
+		}
+		if (pr_done_ms < 95 || pr_done_ms >= 130) {
+			ksft_print_msg("T ended at %lld ms: its next period is at 100\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	case PR_UNTOUCHED:
+		if (pr_pre_cpu_ms > 2) {
+			ksft_print_msg("T used %lld ms before its change: H did not delay it\n",
+				       (long long)pr_pre_cpu_ms);
+			goto out;
+		}
+		if (pr_done_ms < 95 || pr_done_ms >= 130) {
+			ksft_print_msg("T ended at %lld ms: its next period is at 100\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	case PR_RAISED:
+		if (pr_pre_cpu_ms > 6) {
+			ksft_print_msg("T used %lld ms before its change: H did not delay it\n",
+				       (long long)pr_pre_cpu_ms);
+			goto out;
+		}
+		if (pr_done_ms < 110 || pr_done_ms >= 140) {
+			ksft_print_msg("T ended at %lld ms: its next period is at about 115\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&pr_h_ready);
+	sem_destroy(&pr_h_go);
+	return ret;
+}
+
+/*
+ * Shorten the period of a running task:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 100ms, at 0ms. It
+ *    spins 3ms.
+ * 2. T changes its period to 50ms, and spins 9ms more. It runs out of
+ *    runtime at about 10ms.
+ *
+ * The period in progress keeps its start. So T's next period starts at
+ * 50ms, and T ends its spin at about 52ms. The case fails if T ends
+ * before 45ms, or at 80ms or later.
+ */
+static int period_shrunk_running(void)
+{
+	return period_rule_case(PR_SHRUNK);
+}
+
+/*
+ * Lengthen the period of a running task:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 50ms, at 0ms. It
+ *    spins 3ms.
+ * 2. T changes its period to 100ms, and spins 4ms more. It then spins
+ *    5ms more, and runs out of runtime at about 10ms.
+ *
+ * The job in progress keeps its deadline, at 20ms: T must end its first
+ * 7ms at once. T's next period starts at 100ms, and T ends at about
+ * 102ms. The case fails if T ends its first 7ms at 30ms or later, or if
+ * it ends before 95ms, or at 130ms or later.
+ */
+static int period_grown_running(void)
+{
+	return period_rule_case(PR_GROWN);
+}
+
+/*
+ * Lengthen the period of a task that has not run yet in its period:
+ * 1. H, a deadline task of 6ms in 10ms, every 100ms, sleeps.
+ * 2. T becomes a deadline task of 10ms in 20ms, every 50ms, at 0ms, and
+ *    wakes H. H has the earlier deadline. It runs for 5ms.
+ * 3. T runs from 5ms, with its 10ms of runtime and 15ms to its deadline.
+ *    It changes its period to 100ms, and spins 9ms.
+ *
+ * T keeps its job, with the runtime that the new density allows before
+ * its deadline: 10ms in 20ms over the 15ms left, 7.5ms. Its next period
+ * is its release plus the new period, at 100ms. T runs 7.5ms, waits, and
+ * ends at about 101ms. The case fails if T ends before 95ms, or at 130ms
+ * or later.
+ */
+static int period_grown_untouched(void)
+{
+	return period_rule_case(PR_UNTOUCHED);
+}
+
+/*
+ * Raise the runtime of a task late in its period:
+ * 1. H, a deadline task of 62ms in 65ms, every 100ms, sleeps.
+ * 2. T becomes a deadline task of 10ms every 100ms, at 0ms. It spins 2ms,
+ *    and wakes H. H has the earlier deadline. It runs for 60ms.
+ * 3. T runs from about 62ms, with 8ms left. It raises its runtime to
+ *    15ms, and spins 12ms.
+ *
+ * T used 2ms by 62ms, less than its share: it has no debt. It keeps its
+ * job and its 8ms. Its next period starts once those 8ms are paid at the
+ * new bandwidth, at about 115ms. T runs its 8ms, waits, and ends at about
+ * 119ms. The case fails if T ends before 110ms, or at 140ms or later.
+ */
+static int runtime_raised_waited(void)
+{
+	return period_rule_case(PR_RAISED);
+}
+
+static atomic_int flip_stop;
+static _Atomic pid_t flip_tid;
+static _Atomic long long flip_cpu_ms;
+static sem_t flip_ready;
+
+/*
+ * Run as T of params_flip_no_gain(). Become a deadline task of 10ms
+ * every 100ms, and spin until flip_stop. Store the CPU time used in
+ * flip_cpu_ms. Return NULL, or 1 on an error.
+ */
+static void *flip_t(void *arg)
+{
+	uint64_t c0;
+	int err;
+
+	flip_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	sem_post(&flip_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	c0 = thread_time_ns();
+	while (!flip_stop)
+		;
+	flip_cpu_ms = (thread_time_ns() - c0) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Flip the parameters of a task that never sleeps:
+ * 1. T becomes a deadline task of 10ms every 100ms, and spins.
+ * 2. For 500ms, the main thread changes T every 3ms: to 2ms every 20ms,
+ *    then back to 10ms every 100ms. Both are 10% of a CPU. P has one
+ *    CPU, so the main thread mostly runs while T is throttled.
+ *
+ * No change may give T runtime. T must get about 10% of the 500ms, plus
+ * its first 10ms. The case fails if T gets 90ms of CPU time or more, or
+ * if the kernel logs "sched: DL replenish lagged too much". It skips if
+ * that message was logged before: the kernel prints it once.
+ */
+static int params_flip_no_gain(void)
+{
+	void *t_ret = NULL;
+	int err = 0, had, i, ret = KSFT_FAIL;
+	uint64_t end;
+	pthread_t t;
+
+	had = klog_has(DL_LAG_MSG);
+	if (had) {
+		ksft_print_msg(had < 0 ? "the kernel log cannot be read\n" :
+			       "the lag message was logged before this case\n");
+		return KSFT_SKIP;
+	}
+	if (sem_init(&flip_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	flip_stop = 0;
+	flip_cpu_ms = -1;
+	if (pthread_create(&t, NULL, flip_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&flip_ready, 5000)) {
+		flip_stop = 1;
+		join(t);
+		goto out;
+	}
+	end = now_ns() + 500 * NSEC_PER_MSEC;
+	for (i = 0; !err && now_ns() < end; i++) {
+		sleep_ns(3 * NSEC_PER_MSEC);
+		if (i & 1)
+			err = set_deadline(flip_tid, 10 * NSEC_PER_MSEC, PERIOD);
+		else
+			err = set_deadline(flip_tid, 2 * NSEC_PER_MSEC, PERIOD / 5);
+	}
+	flip_stop = 1;
+	pthread_join(t, &t_ret);
+	if (err) {
+		ksft_print_msg("T could not change: %s\n", strerror(-err));
+		goto out;
+	}
+	if (t_ret || flip_cpu_ms < 0)
+		goto out;	/* T said why */
+	if (flip_cpu_ms >= 90) {
+		ksft_print_msg("T got %lld ms of CPU time in 500ms, with 10%% of a CPU\n",
+			       (long long)flip_cpu_ms);
+		goto out;
+	}
+	if (klog_has(DL_LAG_MSG) == 1) {
+		ksft_print_msg("a refill logged \"%s\"\n", DL_LAG_MSG);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&flip_ready);
+	return ret;
+}
+
+static sem_t vic_b_ready, vic_go;
+static atomic_int vic_stop, vic_b_err;
+static _Atomic unsigned long long vic_t0;
+static _Atomic long long vic_b_done_ms;
+
+/*
+ * Run as B of period_shrunk_no_burst(). Become a deadline task of 40ms
+ * every 100ms, and wait for vic_go. Then spin 39ms, and store in
+ * vic_b_done_ms the time at which the spin ends. Return NULL, or 1 on an
+ * error.
+ */
+static void *vic_b(void *arg)
+{
+	int err = set_deadline(0, 40 * NSEC_PER_MSEC, PERIOD);
+
+	vic_b_err = err;
+	sem_post(&vic_b_ready);
+	if (err) {
+		ksft_print_msg("B refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&vic_go);
+	if (!vic_stop) {
+		spin_ns(39 * NSEC_PER_MSEC);
+		vic_b_done_ms = (now_ns() - vic_t0) / NSEC_PER_MSEC;
+	}
+	if (set_other(0))
+		ksft_print_msg("B cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as A of period_shrunk_no_burst(). Its comment has the steps. Return
+ * NULL, or 1 on an error.
+ */
+static void *vic_a(void *arg)
+{
+	int err = set_deadline(0, 40 * NSEC_PER_MSEC, PERIOD);
+
+	if (err) {
+		ksft_print_msg("A refused as a deadline task: %s\n", strerror(-err));
+		vic_stop = 1;
+		sem_post(&vic_go);
+		return (void *)1;
+	}
+	vic_t0 = now_ns();
+	sem_post(&vic_go);
+	spin_ns(39 * NSEC_PER_MSEC + NSEC_PER_MSEC / 2);
+	err = set_deadline(0, 400 * NSEC_PER_USEC, NSEC_PER_MSEC);
+	if (err)
+		ksft_print_msg("A could not change: %s\n", strerror(-err));
+	while (!vic_stop)
+		;
+	if (set_other(0))
+		ksft_print_msg("A cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * A task that used its runtime shortens its period, at the same
+ * bandwidth. P has one CPU:
+ * 1. B, a deadline task of 40ms every 100ms, sleeps for more than its
+ *    period.
+ * 2. A becomes a deadline task of 40ms every 100ms, at 0ms, and wakes B.
+ *    B's wakeup starts a period, with a deadline just after A's.
+ * 3. A spins 39.5ms. It then changes to 0.4ms every 1ms, and spins on.
+ * 4. B runs when A is throttled, and spins 39ms.
+ *
+ * A ran about 24ms ahead of its share. Repaid at its new bandwidth, that
+ * debt puts A's next period at about 99ms, and B ends at about 79ms. If the change gave A a
+ * period at once, A would run 0.4ms of every 1ms from 40ms, with
+ * deadlines before B's. B would end at about 105ms, after its deadline.
+ * The case fails if B ends at 95ms or later.
+ */
+static int period_shrunk_no_burst(void)
+{
+	void *a_ret = NULL, *b_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t a, b;
+
+	if (sem_init(&vic_b_ready, 0, 0) || sem_init(&vic_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	vic_stop = 0;
+	vic_b_done_ms = -1;
+	if (pthread_create(&b, NULL, vic_b, NULL)) {
+		ksft_print_msg("the B thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&vic_b_ready, 5000) || vic_b_err) {
+		vic_stop = 1;
+		sem_post(&vic_go);
+		join(b);
+		goto out;	/* B said why */
+	}
+	sleep_ns(PERIOD + 10 * NSEC_PER_MSEC);
+	if (pthread_create(&a, NULL, vic_a, NULL)) {
+		ksft_print_msg("the A thread could not start\n");
+		vic_stop = 1;
+		sem_post(&vic_go);
+		join(b);
+		goto out;
+	}
+	pthread_join(b, &b_ret);
+	vic_stop = 1;
+	pthread_join(a, &a_ret);
+	if (a_ret || b_ret || vic_b_done_ms < 0)
+		goto out;	/* the thread said why */
+	if (vic_b_done_ms >= 95) {
+		ksft_print_msg("B ended at %lld ms: A ran in new periods before 99ms\n",
+			       (long long)vic_b_done_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&vic_b_ready);
+	sem_destroy(&vic_go);
+	return ret;
+}
+
+static sem_t cmix_b_ready, cmix_go;
+static atomic_int cmix_stop, cmix_b_err;
+static _Atomic unsigned long long cmix_t0;
+static _Atomic long long cmix_b_done_ms;
+
+/*
+ * Run as B of constrained_after_job(). Become a deadline task of 150ms
+ * every 200ms, and wait for cmix_go. Then spin 148ms, and store in
+ * cmix_b_done_ms the time at which the spin ends. Return NULL, or 1 on an
+ * error.
+ */
+static void *cmix_b(void *arg)
+{
+	int err = set_deadline(0, 150 * NSEC_PER_MSEC, 200 * NSEC_PER_MSEC);
+
+	cmix_b_err = err;
+	sem_post(&cmix_b_ready);
+	if (err) {
+		ksft_print_msg("B refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&cmix_go);
+	if (!cmix_stop) {
+		spin_ns(148 * NSEC_PER_MSEC);
+		cmix_b_done_ms = (now_ns() - cmix_t0) / NSEC_PER_MSEC;
+	}
+	if (set_other(0))
+		ksft_print_msg("B cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as A of constrained_after_job(). Its comment has the steps. Return
+ * NULL, or 1 on an error.
+ */
+static void *cmix_a(void *arg)
+{
+	int err = set_deadline(0, 15 * NSEC_PER_MSEC, PERIOD);
+
+	if (err) {
+		ksft_print_msg("A refused as a deadline task: %s\n", strerror(-err));
+		cmix_stop = 1;
+		sem_post(&cmix_go);
+		return (void *)1;
+	}
+	cmix_t0 = now_ns();
+	sem_post(&cmix_go);
+	spin_ns(14 * NSEC_PER_MSEC + NSEC_PER_MSEC / 2);
+	err = set_constrained(0, 18 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+			      120 * NSEC_PER_MSEC);
+	if (err)
+		ksft_print_msg("A could not change: %s\n", strerror(-err));
+	while (!cmix_stop)
+		;
+	if (set_other(0))
+		ksft_print_msg("A cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * A task that used most of its runtime moves to a constrained deadline,
+ * at the same bandwidth. P has one CPU:
+ * 1. B makes itself a deadline task of 150ms every 200ms. It sleeps for
+ *    more than its period.
+ * 2. A makes itself a deadline task of 15ms every 100ms, at 0ms, and
+ *    wakes B. A's deadline is 100ms. B's wakeup starts a period, with a
+ *    deadline at 200ms.
+ * 3. A spins 14.5ms. It then changes itself to 18ms in 20ms, every
+ *    120ms, and spins on.
+ * 4. A is throttled at 15ms, when its runtime runs out. B then runs, and
+ *    spins 148ms.
+ *
+ * A's job of the old parameters counts as a whole job of the new ones.
+ * It keeps its deadline of 100ms, so it counts as released at
+ * 100 - 20 = 80ms. A's next job then starts at 80 + 120 = 200ms, and B
+ * ends at about 163ms. If A's next job started at 120ms, its deadline at
+ * 140ms would come before B's. A would preempt B for 18ms, and B would
+ * end at about 181ms. The case fails if B ends at 172ms or later.
+ */
+static int constrained_after_job(void)
+{
+	void *a_ret = NULL, *b_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t a, b;
+
+	if (sem_init(&cmix_b_ready, 0, 0) || sem_init(&cmix_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	cmix_stop = 0;
+	cmix_b_done_ms = -1;
+	if (pthread_create(&b, NULL, cmix_b, NULL)) {
+		ksft_print_msg("the B thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&cmix_b_ready, 5000) || cmix_b_err) {
+		cmix_stop = 1;
+		sem_post(&cmix_go);
+		join(b);
+		goto out;	/* B said why */
+	}
+	sleep_ns(210 * NSEC_PER_MSEC);
+	if (pthread_create(&a, NULL, cmix_a, NULL)) {
+		ksft_print_msg("the A thread could not start\n");
+		cmix_stop = 1;
+		sem_post(&cmix_go);
+		join(b);
+		goto out;
+	}
+	pthread_join(b, &b_ret);
+	cmix_stop = 1;
+	pthread_join(a, &a_ret);
+	if (a_ret || b_ret || cmix_b_done_ms < 0)
+		goto out;	/* the thread said why */
+	if (cmix_b_done_ms >= 172) {
+		ksft_print_msg("B ended at %lld ms: A's next job came before 200ms\n",
+			       (long long)cmix_b_done_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&cmix_b_ready);
+	sem_destroy(&cmix_go);
+	return ret;
+}
+
+static _Atomic long long grow_back_ms;
+
+/*
+ * Run as T of deadline_grows_running(). Its comment has the steps. Store
+ * in grow_back_ms how late T runs after its sleep. Return NULL, or 1 on
+ * an error.
+ */
+static void *grow_t(void *arg)
+{
+	struct timespec ts;
+	uint64_t end;
+	int err;
+
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	if (!err) {
+		sched_yield();
+		err = set_constrained(0, 10 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC,
+				      PERIOD);
+	}
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		set_other(0);
+		return (void *)1;
+	}
+	sched_yield();
+	end = now_ns() + 30 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	grow_back_ms = (now_ns() - end) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Lengthen the relative deadline of a task that its replenishment timer
+ * refills:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 100ms, and yields.
+ *    The timer refills it at the start of its next period.
+ * 2. T changes itself to 10ms in 50ms, every 100ms, and yields again.
+ * 3. The timer refills T at the start of its next period. T then sleeps
+ *    30ms. It wakes up before its new deadline, 50ms into the period.
+ *
+ * T must run at once. With the old relative deadline, its deadline would
+ * be 20ms into the period, and the wakeup would throttle T until the next
+ * period. The case fails if T runs 20ms or more after its wakeup.
+ */
+static int deadline_grows_running(void)
+{
+	void *t_ret = NULL;
+	pthread_t t;
+
+	grow_back_ms = -1;
+	if (pthread_create(&t, NULL, grow_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		return KSFT_FAIL;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || grow_back_ms < 0)
+		return KSFT_FAIL;	/* T said why */
+	if (grow_back_ms >= 20) {
+		ksft_print_msg("T ran %lld ms after its wakeup\n",
+			       (long long)grow_back_ms);
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+static sem_t gap_h_ready, gap_h_go, gap_h_end;
+static atomic_int gap_h_err;
+static _Atomic long long gap_used_ms, gap_back_ms;
+
+/*
+ * Run as H of constrained_gap_change_running(). Become a deadline task of
+ * 40ms in 45ms, every 100ms, and wait for gap_h_go. Then spin for 35ms of
+ * CPU time, and wait for gap_h_end. Return NULL, or 1 on an error.
+ */
+static void *gap_h(void *arg)
+{
+	int err = set_constrained(0, 40 * NSEC_PER_MSEC, 45 * NSEC_PER_MSEC, PERIOD);
+
+	gap_h_err = err;
+	sem_post(&gap_h_ready);
+	if (err) {
+		ksft_print_msg("H refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&gap_h_go);
+	spin_ns(35 * NSEC_PER_MSEC);
+	sem_wait_sig(&gap_h_end);
+	if (set_other(0))
+		ksft_print_msg("H cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as T of constrained_gap_change_running(). Its comment has the
+ * steps. Store in gap_used_ms the CPU time T used until 55ms, and in
+ * gap_back_ms the time at which T runs again after its change. Return
+ * NULL, or 1 on an error.
+ */
+static void *gap_t(void *arg)
+{
+	uint64_t t0, c0;
+	int err;
+
+	err = set_constrained(0, 40 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	t0 = now_ns();
+	c0 = thread_time_ns();
+	sem_post(&gap_h_go);
+	while (now_ns() - t0 < 55 * NSEC_PER_MSEC)
+		;
+	gap_used_ms = (thread_time_ns() - c0) / NSEC_PER_MSEC;
+	err = set_constrained(0, 39 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC, PERIOD);
+	gap_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+	if (err)
+		ksft_print_msg("T could not change: %s\n", strerror(-err));
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Change the parameters of a running task past its deadline, before its
+ * next period. P has one CPU:
+ * 1. H, a deadline task of 40ms in 45ms, every 100ms, waits.
+ * 2. T becomes a deadline task of 40ms in 50ms, every 100ms, and wakes H.
+ *    H has the earlier deadline. It runs for 35ms.
+ * 3. T runs from 35ms. At 50ms it is past its deadline, with runtime
+ *    left.
+ * 4. At 55ms, T changes its runtime to 39ms. The enqueue of the change
+ *    throttles it until its next period, at 100ms.
+ *
+ * T must then leave the CPU until 100ms. Its CPU time does not show it:
+ * a throttled task that keeps running is not charged. So T reads the time
+ * when its change returns. The case fails before 90ms.
+ */
+static int constrained_gap_change_running(void)
+{
+	void *h_ret = NULL, *t_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t h, t;
+
+	if (sem_init(&gap_h_ready, 0, 0) || sem_init(&gap_h_go, 0, 0) ||
+	    sem_init(&gap_h_end, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	gap_used_ms = -1;
+	gap_back_ms = -1;
+	if (pthread_create(&h, NULL, gap_h, NULL)) {
+		ksft_print_msg("the H thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&gap_h_ready, 5000) || gap_h_err) {
+		sem_post(&gap_h_go);
+		sem_post(&gap_h_end);
+		join(h);
+		goto out;	/* H said why */
+	}
+	if (pthread_create(&t, NULL, gap_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		sem_post(&gap_h_go);
+		sem_post(&gap_h_end);
+		join(h);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	sem_post(&gap_h_go);	/* if T never woke H */
+	sem_post(&gap_h_end);
+	pthread_join(h, &h_ret);
+	if (t_ret || h_ret || gap_back_ms < 0)
+		goto out;	/* the thread said why */
+	if (gap_used_ms > 30) {
+		ksft_print_msg("T used %lld ms of its first 55: H did not delay it\n",
+			       (long long)gap_used_ms);
+		goto out;
+	}
+	if (gap_back_ms < 90) {
+		ksft_print_msg("T ran again at %lld ms, throttled until 100\n",
+			       (long long)gap_back_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&gap_h_ready);
+	sem_destroy(&gap_h_go);
+	sem_destroy(&gap_h_end);
+	return ret;
+}
+
+/*
+ * Return the absolute deadline of the deadline task @tid, in ns of the rq
+ * clock, from dl.deadline in /proc/<tid>/sched. Return -1 if it cannot be
+ * read.
+ */
+static long long dl_deadline_of(pid_t tid)
+{
+	char path[64], line[256];
+	long long d = -1;
+	FILE *f;
+
+	snprintf(path, sizeof(path), "/proc/%d/sched", tid);
+	f = fopen(path, "r");
+	if (!f)
+		return -1;
+	while (fgets(line, sizeof(line), f)) {
+		char *val = strchr(line, ':');
+
+		if (!strncmp(line, "dl.deadline", 11) && val) {
+			d = atoll(val + 1);
+			break;
+		}
+	}
+	fclose(f);
+	return d;
+}
+
+/* Milliseconds from @from to @to, both from now_ns(). */
+#define MS_FROM(from, to)	((long long)((int64_t)((to) - (from)) / (int64_t)NSEC_PER_MSEC))
+
+/*
+ * A task of 10ms in 20ms, every 500ms, entered the class at @start. It
+ * leaves the class early in its second period. It keeps its bandwidth
+ * until its 0-lag time, before its third period at 1000ms. Wait for that
+ * period, so that measured() probes after the release.
+ */
+static void wait_third_period(uint64_t start)
+{
+	uint64_t end = start + 10 * PERIOD + 50 * NSEC_PER_MSEC, now = now_ns();
+
+	if (start && now < end)
+		sleep_ns(end - now);
+}
+
+static _Atomic uint32_t rb2_pi;
+static atomic_int rb2_t_locking;
+static _Atomic pid_t rb2_t_tid;
+static _Atomic uint64_t rb2_t_start, rb2_t_got;
+
+/*
+ * Run as T of reenter_pi_blocked_in_gap(). Become a deadline task of 10ms
+ * in 20ms, every 500ms. Spin 2ms of CPU time, then take rb2_pi with
+ * FUTEX_LOCK_PI. Once T holds it, store the time and unlock. Return NULL,
+ * or 1 on an error.
+ */
+static void *rb2_t(void *arg)
+{
+	uint32_t tid = gettid_();
+	int err;
+
+	rb2_t_tid = tid;
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	rb2_t_start = now_ns();
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		rb2_t_locking = -1;
+		return (void *)1;
+	}
+	spin_ns(2 * NSEC_PER_MSEC);
+	rb2_t_locking = 1;
+	if (syscall(SYS_futex, &rb2_pi, FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG,
+		    0, NULL, NULL, 0)) {
+		ksft_print_msg("FUTEX_LOCK_PI: %s\n", strerror(errno));
+		set_other(0);
+		return (void *)1;
+	}
+	rb2_t_got = now_ns();
+	if (!atomic_compare_exchange_strong(&rb2_pi, &tid, 0))
+		syscall(SYS_futex, &rb2_pi, FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG,
+			0, NULL, NULL, 0);
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * A task blocked on an rt_mutex leaves the deadline class in its
+ * constrained gap and comes back. The main thread holds the PI futex
+ * rb2_pi. P has one CPU:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    spins 2ms and blocks on rb2_pi. Its deadline is 20ms.
+ * 2. At 40ms, T is past its deadline and before its next period, at
+ *    500ms. The main thread switches T to SCHED_OTHER, then back to
+ *    SCHED_DEADLINE with the same parameters. T still waits on rb2_pi.
+ * 3. At about 45ms, the main thread unlocks rb2_pi.
+ *
+ * T used 2ms of its 10ms. Past its deadline, it gets no more runtime in
+ * that period: a wakeup would throttle it until 500ms. Leaving the class
+ * and coming back must not give it a new period before then. The case
+ * fails if T gets rb2_pi before 490ms.
+ */
+static int reenter_pi_blocked_in_gap(void)
+{
+	long long dl_gap = -1, dl_back = -1;
+	uint64_t back_at = 0, unlock_at;
+	int ret = KSFT_FAIL, err;
+	void *t_ret = NULL;
+	pthread_t t;
+
+	rb2_pi = gettid_();
+	rb2_t_locking = 0;
+	rb2_t_tid = 0;
+	rb2_t_start = 0;
+	rb2_t_got = 0;
+	if (pthread_create(&t, NULL, rb2_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		return KSFT_FAIL;
+	}
+	if (wait_for(1000, rb2_t_locking &&
+		     (rb2_t_locking < 0 || (proc_state_of(rb2_t_tid) == 'S' &&
+					    (rb2_pi & FUTEX_WAITERS)))) ||
+	    rb2_t_locking < 0) {
+		ksft_print_msg("T never blocked on rb2_pi\n");
+		goto out;
+	}
+	while (now_ns() - rb2_t_start < 40 * NSEC_PER_MSEC)
+		sleep_ns(NSEC_PER_MSEC);
+	dl_gap = dl_deadline_of(rb2_t_tid);
+	err = set_other(rb2_t_tid);
+	if (err) {
+		ksft_print_msg("T cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	err = set_constrained(rb2_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	back_at = now_ns();
+	if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		goto out;
+	}
+	dl_back = dl_deadline_of(rb2_t_tid);
+	if (proc_state_of(rb2_t_tid) != 'S' || !(rb2_pi & FUTEX_WAITERS)) {
+		ksft_print_msg("T no longer waits on rb2_pi\n");
+		goto out;
+	}
+	sleep_ns(5 * NSEC_PER_MSEC);
+	ret = KSFT_PASS;
+out:
+	unlock_at = now_ns();
+	{
+		uint32_t tid = gettid_();
+
+		if (!atomic_compare_exchange_strong(&rb2_pi, &tid, 0))
+			syscall(SYS_futex, &rb2_pi, FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG,
+				0, NULL, NULL, 0);
+	}
+	if (pthread_join(t, &t_ret) || t_ret || ret != KSFT_PASS)
+		return KSFT_FAIL;	/* the thread said why */
+	wait_third_period(rb2_t_start);
+	ksft_print_msg("T back at %lld ms, deadline moved by %lld ms; next period at 500 ms\n",
+		       MS_FROM(rb2_t_start, back_at),
+		       dl_back < 0 || dl_gap < 0 ? -1LL :
+		       (dl_back - dl_gap) / (long long)NSEC_PER_MSEC);
+	ksft_print_msg("(0: kept, %lld: new period); unlock %lld ms; T got the lock %lld ms\n",
+		       MS_FROM(rb2_t_start, back_at),
+		       MS_FROM(rb2_t_start, unlock_at), MS_FROM(rb2_t_start, rb2_t_got));
+	if (MS_FROM(rb2_t_start, rb2_t_got) < 490) {
+		ksft_print_msg("T ran before its next period\n");
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+static int ra_fd[2];
+static atomic_int ra_t_asleep;
+static _Atomic pid_t ra_t_tid;
+static _Atomic uint64_t ra_t_start, ra_t_run;
+
+/*
+ * Run as T of reenter_asleep_case(). Become a deadline task of 10ms in
+ * 20ms, every 500ms. Spin 2ms of CPU time, then sleep in a read of
+ * ra_fd[0]. Once woken, store the time and leave SCHED_DEADLINE. Return
+ * NULL, or 1 on an error.
+ */
+static void *ra_t(void *arg)
+{
+	char c;
+	int err;
+
+	ra_t_tid = gettid_();
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	ra_t_start = now_ns();
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		ra_t_asleep = -1;
+		return (void *)1;
+	}
+	spin_ns(2 * NSEC_PER_MSEC);
+	ra_t_asleep = 1;
+	if (read(ra_fd[0], &c, 1) != 1) {
+		ksft_print_msg("T: read: %s\n", strerror(errno));
+		set_other(0);
+		return (void *)1;
+	}
+	ra_t_run = now_ns();
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * The same as reenter_pi_blocked_in_gap(), without the rt_mutex. P has
+ * one CPU:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    spins 2ms and sleeps in a read of a pipe, with 8ms left. Its
+ *    deadline is 20ms. Its 0-lag time is 100ms.
+ * 2. At @at_ms, T is past its deadline and before its next period, at
+ *    500ms. The main thread switches T to SCHED_OTHER, then back to
+ *    SCHED_DEADLINE with the same parameters.
+ * 3. About 5ms later, the main thread wakes T up.
+ *
+ * Leaving the class and coming back must not give T a new period before
+ * 500ms. The case fails if T runs after its wakeup before 490ms.
+ */
+static int reenter_asleep_case(int at_ms)
+{
+	long long dl_gap = -1, dl_back = -1;
+	uint64_t back_at = 0, wake_at = 0;
+	int ret = KSFT_FAIL, err;
+	void *t_ret = NULL;
+	pthread_t t;
+
+	if (pipe(ra_fd)) {
+		ksft_print_msg("pipe: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	ra_t_asleep = 0;
+	ra_t_tid = 0;
+	ra_t_start = 0;
+	ra_t_run = 0;
+	if (pthread_create(&t, NULL, ra_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto close;
+	}
+	if (wait_for(1000, ra_t_asleep &&
+		     (ra_t_asleep < 0 || proc_state_of(ra_t_tid) == 'S')) ||
+	    ra_t_asleep < 0) {
+		ksft_print_msg("T never slept\n");
+		goto out;
+	}
+	while (now_ns() - ra_t_start < (uint64_t)at_ms * NSEC_PER_MSEC)
+		sleep_ns(NSEC_PER_MSEC);
+	dl_gap = dl_deadline_of(ra_t_tid);
+	err = set_other(ra_t_tid);
+	if (err) {
+		ksft_print_msg("T cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	err = set_constrained(ra_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	back_at = now_ns();
+	if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		goto out;
+	}
+	dl_back = dl_deadline_of(ra_t_tid);
+	if (proc_state_of(ra_t_tid) != 'S') {
+		ksft_print_msg("T is no longer asleep\n");
+		goto out;
+	}
+	sleep_ns(5 * NSEC_PER_MSEC);
+	ret = KSFT_PASS;
+out:
+	wake_at = now_ns();
+	if (write(ra_fd[1], "x", 1) != 1)
+		ksft_print_msg("write: %s\n", strerror(errno));
+	if (pthread_join(t, &t_ret) || t_ret)
+		ret = KSFT_FAIL;	/* the thread said why */
+close:
+	close(ra_fd[0]);
+	close(ra_fd[1]);
+	wait_third_period(ra_t_start);
+	if (ret != KSFT_PASS)
+		return KSFT_FAIL;
+	ksft_print_msg("T back at %lld ms, deadline %s%lld ms; next period at 500 ms\n",
+		       MS_FROM(ra_t_start, back_at),
+		       dl_back == 0 ? "is 0, moved by " : "moved by ",
+		       dl_back < 0 || dl_gap < 0 ? -1LL :
+		       (dl_back - dl_gap) / (long long)NSEC_PER_MSEC);
+	ksft_print_msg("T woken at %lld ms, ran at %lld ms\n",
+		       MS_FROM(ra_t_start, wake_at), MS_FROM(ra_t_start, ra_t_run));
+	if (MS_FROM(ra_t_start, ra_t_run) < 490) {
+		ksft_print_msg("T ran before its next period\n");
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+/* Run reenter_asleep_case() before T's 0-lag time. */
+static int reenter_asleep_in_gap(void)
+{
+	return reenter_asleep_case(40);
+}
+
+/* Run reenter_asleep_case() after T's 0-lag time, before its next period. */
+static int reenter_asleep_late_in_gap(void)
+{
+	return reenter_asleep_case(150);
+}
+
+static atomic_int rr_t_ready, rr_stop;
+static _Atomic pid_t rr_t_tid;
+static _Atomic uint64_t rr_t_start, rr_back_at, rr_t_ran;
+
+/*
+ * Run as T of reenter_runnable_in_gap(). Become a deadline task of 10ms in
+ * 20ms, every 500ms, and spin until rr_stop. Store in rr_t_ran the first
+ * time T runs more than 2ms after rr_back_at. The 2ms leave out the time T
+ * may run as SCHED_OTHER before it is back. Return NULL, or 1 on an
+ * error.
+ */
+static void *rr_t(void *arg)
+{
+	int err;
+
+	rr_t_tid = gettid_();
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	rr_t_start = now_ns();
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		rr_t_ready = -1;
+		return (void *)1;
+	}
+	rr_t_ready = 1;
+	while (!rr_stop) {
+		uint64_t t = now_ns(), b = rr_back_at;
+
+		if (b && !rr_t_ran && t > b + 2 * NSEC_PER_MSEC)
+			rr_t_ran = t;
+	}
+	return NULL;
+}
+
+/*
+ * The same as reenter_asleep_in_gap(), for a task that stays runnable. P
+ * has one CPU:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms, and
+ *    spins. It is throttled at 10ms, until its next period at 500ms.
+ * 2. At 40ms, the main thread switches T to SCHED_OTHER, then back to
+ *    SCHED_DEADLINE with the same parameters.
+ *
+ * Leaving the class and coming back must not give T a new period before
+ * 500ms. With a new period, T would run at once. The case fails if T runs
+ * from 2ms to 50ms after rr_back_at.
+ */
+static int reenter_runnable_in_gap(void)
+{
+	int ret = KSFT_FAIL, err;
+	void *t_ret = NULL;
+	pthread_t t;
+
+	rr_t_ready = 0;
+	rr_stop = 0;
+	rr_t_tid = 0;
+	rr_t_start = 0;
+	rr_back_at = 0;
+	rr_t_ran = 0;
+	if (pthread_create(&t, NULL, rr_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		return KSFT_FAIL;
+	}
+	if (wait_for(1000, rr_t_ready) || rr_t_ready < 0) {
+		ksft_print_msg("T never started\n");
+		goto out;
+	}
+	while (now_ns() - rr_t_start < 40 * NSEC_PER_MSEC)
+		sleep_ns(NSEC_PER_MSEC);
+	err = set_other(rr_t_tid);
+	if (err) {
+		ksft_print_msg("T cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	/* Store it before the switch back. A T given a new period runs at once. */
+	rr_back_at = now_ns();
+	err = set_constrained(rr_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		goto out;
+	}
+	sleep_ns(50 * NSEC_PER_MSEC);
+	ret = KSFT_PASS;
+out:
+	set_other(rr_t_tid);
+	rr_stop = 1;
+	if (pthread_join(t, &t_ret) || t_ret)
+		ret = KSFT_FAIL;
+	/*
+	 * T left the class in its constrained gap, throttled. It keeps its
+	 * bandwidth until its 0-lag time: its next period, 5 * PERIOD after
+	 * its start, plus its overrun paid back at 10ms every 5 * PERIOD. An
+	 * overrun of a 10ms tick adds 5 * PERIOD. Wait for it, so that
+	 * measured() finds the bandwidth released.
+	 */
+	if (rr_t_start) {
+		uint64_t end = rr_t_start + 10 * PERIOD + 50 * NSEC_PER_MSEC;
+		uint64_t now = now_ns();
+
+		if (now < end)
+			sleep_ns(end - now);
+	}
+	if (ret != KSFT_PASS)
+		return KSFT_FAIL;
+	ksft_print_msg("T back at %lld ms, ran again at %lld ms\n",
+		       MS_FROM(rr_t_start, rr_back_at),
+		       rr_t_ran ? MS_FROM(rr_t_start, rr_t_ran) : -1LL);
+	if (rr_t_ran && rr_t_ran < rr_back_at + 50 * NSEC_PER_MSEC) {
+		ksft_print_msg("T ran before its next period\n");
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
 static pthread_mutex_t pi_lock2;
 static sem_t holder_go;
 static atomic_int holder_holds, chain_waits, donor_done, x_waits, l2_takes;
 static atomic_int chain_rank, x_rank;
-static _Atomic pid_t x_tid;
+static _Atomic pid_t x_tid, fair_tid;
 
 /* The holder thread: take pi_lock2, and hold it until holder_go. */
 static void *l2_holder(void *arg)
@@ -2071,8 +3834,8 @@ static int take_l2_ranked(atomic_int *rank)
  * boost refills its runtime from the donor's 40ms. Then wait on pi_lock2
  * while holding pi_lock. The donor's timeout deboosts the owner during
  * that wait. The owner then has more runtime left than its own 10ms.
- * Return NULL, 1 on an error, or 2 if the spin took over 50ms: the owner
- * was throttled, so it was not boosted.
+ * Return NULL, or 1 on an error. Return 2 if the spin took over 50ms.
+ * The owner was then throttled, so it was not boosted.
  */
 static void *chain_owner(void *arg)
 {
@@ -2187,6 +3950,7 @@ static int pi_init_lock2(void)
 	x_rank = -1;
 	donor_tid = 0;
 	x_tid = 0;
+	fair_tid = 0;
 	return 0;
 }
 
@@ -2285,6 +4049,137 @@ static int deboost_blocked_keeps_order(void)
 	return ret;
 }
 
+static int dl_waiter_spin_ms;
+
+/*
+ * A waiter of pi_lock2 that is a deadline task of 400ms every 1s. It
+ * spins dl_waiter_spin_ms of CPU time once it starts its period, then
+ * waits. It leaves the class at the end.
+ */
+static void *dl_waiter(void *arg)
+{
+	int err;
+
+	fair_tid = gettid_();
+	err = set_deadline(0, 400 * NSEC_PER_MSEC, NSEC_PER_SEC);
+	if (err) {
+		ksft_print_msg("a waiter refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(dl_waiter_spin_ms * NSEC_PER_MSEC);
+	chain_waits = 1;
+	err = take_l2_ranked(&chain_rank);
+	if (set_other(0))
+		ksft_print_msg("a waiter cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+static int setattr_blocked_case(int reenter);
+
+/*
+ * Check the order of the waiters of pi_lock2 when sched_setattr() changes
+ * the parameters of one of them while it waits. The holder has pi_lock2:
+ * 1. W, a deadline task of 400ms every 1s, waits on pi_lock2. Its
+ *    deadline is about 1s ahead.
+ * 2. The other waiter, a deadline task of 5ms every 50ms, waits on
+ *    pi_lock2. Its deadline is about 50ms ahead.
+ * 3. The main thread gives W 1ms every 10ms. W has not run, so it owes
+ *    nothing: it starts a new period at once. Its deadline is 10ms ahead.
+ * 4. The holder drops pi_lock2.
+ *
+ * W must take pi_lock2 first. W is not queued at step 3. Unless its
+ * period is fitted to its new parameters then, its waiter node keeps the
+ * deadline 1s ahead.
+ */
+static int setattr_blocked_new_period(void)
+{
+	return setattr_blocked_case(0);
+}
+
+/*
+ * The same, when W leaves the class and comes back while it waits. W
+ * first spins 100ms: 60ms more than its share, so its 0-lag time is about
+ * 250ms ahead. At step 3, the main thread switches W to SCHED_OTHER, then
+ * back to SCHED_DEADLINE with 3ms every 10ms. W keeps its parameters
+ * until its 0-lag time, so it comes back with that debt. Repaid at 30%,
+ * the debt puts W's next period about 190ms ahead. W must take pi_lock2
+ * after the other waiter. A new period at once, as a wakeup would start,
+ * would let W take it first.
+ */
+static int setattr_blocked_reenter(void)
+{
+	return setattr_blocked_case(1);
+}
+
+/*
+ * Run setattr_blocked_new_period(), or setattr_blocked_reenter() if
+ * @reenter is set.
+ */
+static int setattr_blocked_case(int reenter)
+{
+	void *w_ret = NULL, *x_ret = NULL;
+	int ret = KSFT_FAIL, have_w = 0, have_x = 0, err;
+	pthread_t h, w, x;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (pi_init_lock2()) {
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	if (pthread_create(&h, NULL, l2_holder, NULL)) {
+		ksft_print_msg("the holder thread could not start\n");
+		goto out_fini;
+	}
+	if (wait_for(5000, holder_holds) || holder_holds != 1) {
+		ksft_print_msg("the holder never took pi_lock2\n");
+		goto out;
+	}
+	dl_waiter_spin_ms = reenter ? 100 : 0;
+	have_w = !pthread_create(&w, NULL, dl_waiter, NULL);
+	if (!have_w || wait_for(1000, chain_waits && proc_state_of(fair_tid) == 'S')) {
+		ksft_print_msg("the waiter W never waited on pi_lock2\n");
+		goto out;
+	}
+	have_x = !pthread_create(&x, NULL, early_waiter, NULL);
+	if (!have_x || wait_for(1000, x_waits && proc_state_of(x_tid) == 'S')) {
+		ksft_print_msg("the other waiter never waited on pi_lock2\n");
+		goto out;
+	}
+	err = reenter ? set_other(fair_tid) : 0;
+	if (err) {
+		ksft_print_msg("W cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	err = set_deadline(fair_tid, (reenter ? 3 : 1) * NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	if (err) {
+		ksft_print_msg("new parameters for W refused: %s\n", strerror(-err));
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_post(&holder_go);	/* pi_lock2 goes to its top waiter */
+	if (have_x && pthread_join(x, &x_ret))
+		ret = KSFT_FAIL;
+	if (have_w && pthread_join(w, &w_ret))
+		ret = KSFT_FAIL;
+	join(h);
+	if (w_ret || x_ret) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (ret == KSFT_PASS && !reenter && chain_rank > x_rank) {
+		ksft_print_msg("W took pi_lock2 after the other waiter\n");
+		ret = KSFT_FAIL;
+	} else if (ret == KSFT_PASS && reenter && chain_rank < x_rank) {
+		ksft_print_msg("W took pi_lock2 before the other waiter\n");
+		ret = KSFT_FAIL;
+	}
+out_fini:
+	pthread_mutex_destroy(&pi_lock2);
+	sem_destroy(&holder_go);
+	pi_fini();
+	return ret;
+}
+
 /*
  * The threads of pi_chain_donor_leaves(): O, M, W, Z and Y. leave_tid[]
  * holds their tids. leave_y_ns is the CPU time Y gets in O's window, or
@@ -5937,6 +7832,144 @@ static int params_waking(void)
 	return ret;
 }
 
+/* Two tasks that pass a large runtime back and forth */
+
+#define SW_BIG		(70 * NSEC_PER_MSEC)
+#define SW_SMALL	NSEC_PER_MSEC
+#define SW_MARGIN	(10 * NSEC_PER_MSEC)	/* raise a task of 1ms below this */
+#define SW_SETTLE	(500 * NSEC_PER_MSEC)
+#define SW_WINDOW	(2 * NSEC_PER_SEC)
+#define SW_MAX_SHARE	85			/* fail at this % of P's CPU */
+
+/*
+ * sw_state[i] is 1 once task i is in P, and -1 if it could not enter.
+ * sw_state[2 + i] is the CPU time it used, in us.
+ */
+static atomic_int *sw_state;
+
+/*
+ * Fork task @i of params_swap_overload() into P. It spins, and writes
+ * the CPU time it used to sw_state[2 + @i]. Return its pid, or -1.
+ */
+static pid_t sw_task(int i)
+{
+	pid_t pid = fork_child("a task of the swap");
+	uint64_t c0;
+
+	if (pid)
+		return pid;
+	if (enter(cg_p, getpid())) {
+		sw_state[i] = -1;
+		_exit(1);
+	}
+	c0 = thread_time_ns();
+	sw_state[i] = 1;
+	for (;;)
+		sw_state[2 + i] = (thread_time_ns() - c0) / NSEC_PER_USEC;
+}
+
+/*
+ * Pass a runtime of 70ms back and forth between two tasks, as in
+ * Example 1 of "On the Defectiveness of SCHED_DEADLINE w.r.t. Tardiness
+ * and Affinities, and a Partial Fix", Tang, Anderson and Abeni, RTNS
+ * 2021. P has one CPU. A and B are processes in P that spin. The main
+ * process, outside P, changes their parameters with sched_setattr():
+ * 1. It makes A a deadline task of 70ms every 100ms. This releases a
+ *    job of 70ms. It then cuts the runtime of A to 1ms.
+ * 2. It does the same with B.
+ * 3. For 2.5s, it polls the runtime left of A and B in /proc. It cuts a
+ *    task of 70ms to 1ms once the task is refilled. It raises a task of
+ *    1ms to 70ms when less than 10ms is left, if the other one is a task
+ *    of 1ms. The next job of the raised task then gets 70ms.
+ *
+ * Admission control sees at most 71% of the CPU, plus the fair server.
+ * If a change keeps the runtime of the job in progress, every job gets
+ * 70ms. A and B then ask for 140% of the CPU, and get the whole CPU. A
+ * change must cap the runtime left at the new runtime, and keep the debt
+ * of the task. A and B then get no more than their 71%. The case fails if
+ * they get 85% of the CPU or more in the last 2s.
+ *
+ * The paper uses 94ms. P cannot admit 94ms and 1ms: its limit is 95%,
+ * and its fair server takes 5% of it. In the paper, the tardiness also
+ * grows without bound. Here it does not: a change of a task past its
+ * deadline starts a new period. So the case measures the CPU time of A
+ * and B, not their deadlines.
+ */
+static int params_swap_overload(void)
+{
+	uint64_t param[2] = { SW_SMALL, SW_SMALL }, start, t, t0 = 0, t1;
+	int cpu0[2] = { 0, 0 }, err = 0, i, changes = 0, ret = KSFT_FAIL;
+	pid_t pid[2] = { -1, -1 };
+	long long used[2];
+
+	sw_state = mv_state + 8;
+	for (i = 0; i < 4; i++)
+		sw_state[i] = 0;
+	pid[0] = sw_task(0);
+	pid[1] = sw_task(1);
+	if (pid[0] < 0 || pid[1] < 0)
+		goto out;
+	if (wait_for(5000, sw_state[0] && sw_state[1]) ||
+	    sw_state[0] < 0 || sw_state[1] < 0) {
+		ksft_print_msg("the tasks could not enter P\n");
+		goto out;
+	}
+	for (i = 0; i < 2 && !err; i++) {
+		err = set_deadline(pid[i], SW_BIG, PERIOD);
+		if (!err)
+			err = set_deadline(pid[i], SW_SMALL, PERIOD);
+	}
+	if (err) {
+		ksft_print_msg("no room for a task of 70ms in P: %s\n", strerror(-err));
+		ret = err == -EBUSY ? KSFT_SKIP : KSFT_FAIL;
+		goto out;
+	}
+	start = now_ns();
+	while (!err && (t = now_ns()) < start + SW_SETTLE + SW_WINDOW) {
+		if (!t0 && t >= start + SW_SETTLE) {
+			t0 = t;
+			cpu0[0] = sw_state[2];
+			cpu0[1] = sw_state[3];
+		}
+		for (i = 0; i < 2 && !err; i++) {
+			long long left = dl_runtime_left(pid[i]);
+			uint64_t to;
+
+			if (param[i] == SW_BIG && left > (long long)SW_BIG / 2)
+				to = SW_SMALL;
+			else if (param[i] == SW_SMALL && left < (long long)SW_MARGIN &&
+				 param[!i] == SW_SMALL)
+				to = SW_BIG;
+			else
+				continue;
+			err = set_deadline(pid[i], to, PERIOD);
+			param[i] = to;
+			changes++;
+		}
+		sleep_ns(100 * NSEC_PER_USEC);
+	}
+	t1 = now_ns();
+	used[0] = sw_state[2] - cpu0[0];
+	used[1] = sw_state[3] - cpu0[1];
+	if (err) {
+		ksft_print_msg("a change refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (100000 * (used[0] + used[1]) >= SW_MAX_SHARE * (long long)(t1 - t0)) {
+		ksft_print_msg("A %lld%%, B %lld%% of the CPU, %d changes\n",
+			       100000 * used[0] / (long long)(t1 - t0),
+			       100000 * used[1] / (long long)(t1 - t0), changes);
+		ksft_print_msg("A and B got %d%% or more, with 71%% admitted\n",
+			       SW_MAX_SHARE);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(pid[0]);
+	reap(pid[1]);
+	return ret;
+}
+
 /* A random mix of the transitions above */
 
 #define MIX_WORKERS	6
@@ -10495,13 +12528,37 @@ static const struct p_case {
 	{ "params_shrunk_long_period", params_shrunk_long_period, MEASURED_IN_P },
 	{ "params_throttled", params_throttled, MEASURED_IN_P },
 	{ "params_refused", params_refused, IN_P },
+	{ "params_return_full", params_return_full, MEASURED_IN_P },
 	{ "params_keep_class_change", params_keep_class_change, MEASURED_IN_P },
 	{ "params_keep_boosted", params_keep_boosted, MEASURED_IN_P },
 	{ "boosted_owner_policy", boosted_owner_policy, MEASURED_IN_P },
 	{ "deboost_resets_period", deboost_resets_period, MEASURED_IN_P },
 	{ "deboost_keeps_own_runtime", deboost_keeps_own_runtime, MEASURED_IN_P },
+	{ "return_running_new_params", return_running_new_params, MEASURED_IN_P },
 	{ "return_asleep_new_params", return_asleep_new_params, MEASURED_IN_P },
+	{ "change_running_new_params", change_running_new_params, MEASURED_IN_P },
+	{ "change_constrained_new_params", change_constrained_new_params, MEASURED_IN_P },
+	{ "wake_constrained_new_params", wake_constrained_new_params, MEASURED_IN_P },
+	{ "constrained_gap_change_running", constrained_gap_change_running, MEASURED_IN_P },
+	{ "reenter_pi_blocked_in_gap", reenter_pi_blocked_in_gap, MEASURED_IN_P },
+	{ "reenter_asleep_in_gap", reenter_asleep_in_gap, MEASURED_IN_P },
+	{ "reenter_asleep_late_in_gap", reenter_asleep_late_in_gap, MEASURED_IN_P },
+	{ "reenter_runnable_in_gap", reenter_runnable_in_gap, MEASURED_IN_P },
+	{ "wake_after_deadline_shrunk", wake_after_deadline_shrunk, MEASURED_IN_P },
+	{ "deadline_grows_running", deadline_grows_running, MEASURED_IN_P },
+	{ "deadline_widened_asleep", deadline_widened_asleep, MEASURED_IN_P },
+	{ "period_shrunk_throttled", period_shrunk_throttled, MEASURED_IN_P },
+	{ "period_shrunk_throttled_started", period_shrunk_throttled_started, MEASURED_IN_P },
+	{ "period_shrunk_running", period_shrunk_running, MEASURED_IN_P },
+	{ "period_grown_running", period_grown_running, MEASURED_IN_P },
+	{ "period_grown_untouched", period_grown_untouched, MEASURED_IN_P },
+	{ "runtime_raised_waited", runtime_raised_waited, MEASURED_IN_P },
+	{ "params_flip_no_gain", params_flip_no_gain, MEASURED_IN_P },
+	{ "period_shrunk_no_burst", period_shrunk_no_burst, MEASURED_IN_P },
+	{ "constrained_after_job", constrained_after_job, MEASURED_IN_P },
 	{ "deboost_blocked_keeps_order", deboost_blocked_keeps_order, MEASURED_IN_P },
+	{ "setattr_blocked_new_period", setattr_blocked_new_period, MEASURED_IN_P },
+	{ "setattr_blocked_reenter", setattr_blocked_reenter, MEASURED_IN_P },
 	{ "pi_chain_donor_leaves", pi_chain_donor_leaves, MEASURED_IN_P },
 	{ "move_asleep", move_asleep, FROM_OUTSIDE },
 	{ "move_throttled", move_throttled, FROM_OUTSIDE },
@@ -10552,6 +12609,7 @@ static const struct p_case {
 	{ "server_states", server_states, FROM_OUTSIDE },
 	{ "server_reclaim", server_reclaim, MEASURED_IN_P },
 	{ "params_waking", params_waking, FROM_OUTSIDE },
+	{ "params_swap_overload", params_swap_overload, FROM_OUTSIDE },
 	{ "random_mix", random_mix, FROM_OUTSIDE },
 	{ "move_normalized", move_normalized, FROM_OUTSIDE },
 };
@@ -11226,6 +13284,17 @@ static const struct hp_case {
 
 #define N_HP_CASES	((int)ARRAY_SIZE(hp_cases))
 
+/*
+ * Return the this_bw of the runqueue of @cpu, or -1 if sched_debug does
+ * not show it.
+ */
+static long this_bw_of(int cpu)
+{
+	long this_bw, running_bw;
+
+	return rq_bw_of(cpu, &this_bw, &running_bw) ? -1 : this_bw;
+}
+
 /* Run the cases of p_cases[], each with a P made anew. */
 static void run_p_cases(void)
 {
@@ -11250,6 +13319,12 @@ static void run_p_cases(void)
 	}
 	for (i = 0; i < N_P_CASES; i++) {
 		const struct p_case *c = &p_cases[i];
+		long long bw0 = total_bw_of(top_cpu(1));
+		long this0[3];
+		int k;
+
+		for (k = 0; k < 3; k++)
+			this0[k] = this_bw_of(top_cpu(k + 1));
 
 		if (ok && make_p()) {
 			remove_p();
@@ -11269,6 +13344,34 @@ static void run_p_cases(void)
 			ret = c->fn();
 		remove_p();
 		server_restore();
+		/*
+		 * A task of the case can keep its bandwidth counted after it
+		 * exits: until its 0-lag time, or until its debt is repaid. Wait
+		 * for that, so that the next case starts from the same total_bw.
+		 * A lower total_bw also ends the wait. Bandwidth lost by a case
+		 * would never come back, and the wait would then cost the whole
+		 * 10s.
+		 */
+		if (bw0 >= 0 &&
+		    wait_for_step(10000, 10 * NSEC_PER_MSEC,
+				  total_bw_of(top_cpu(1)) <= bw0))
+			ksft_print_msg("%s: total_bw %lld after the case, %lld before\n",
+				       c->name, total_bw_of(top_cpu(1)), bw0);
+		/*
+		 * this_bw can stay higher than total_bw shows. A task moved to
+		 * another cpuset while it sleeps leaves its bandwidth in the
+		 * this_bw of its old CPU until it wakes up or dies. Wait for
+		 * the three CPUs that random_mix() checks.
+		 */
+		for (k = 0; k < 3; k++) {
+			int cpu = top_cpu(k + 1);
+
+			if (this0[k] >= 0 &&
+			    wait_for_step(10000, 10 * NSEC_PER_MSEC,
+					  this_bw_of(cpu) <= this0[k]))
+				ksft_print_msg("%s: this_bw of CPU %d %ld after the case, %ld before\n",
+					       c->name, cpu, this_bw_of(cpu), this0[k]);
+		}
 		report(c->name, ret);
 	}
 	if (added && write_file(root, "cgroup.subtree_control", "-cpuset"))
Signature · 1 line
2.47.3
#50 lore raw

Re: [PATCH v14 33/39] selftests/sched: Test parameter changes in deadline_bw_test

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider: - [Medium] selftests/sched: run_p_cases() skips debt wait without debugfs - [Low] selftests/sched…

Thank you for your contribution! Sashiko AI review found 9 potential issues to consider:
- [Medium] selftests/sched: run_p_cases() skips debt wait without debugfs
- [Low] selftests/sched: reenter_runnable_in_gap() 2ms window races with SCHED_OTHER
- [Low] selftests/sched: reenter_pi_blocked_in_gap() fails instead of skipping ENOSYS
- [Low] selftests/sched: constrained_after_job() fails instead of skipping on EBUSY
- [Low] selftests/sched: params_swap_overload() uses unchecked zero t0 on stall
- [Low] selftests/sched: timeout checked before syscall error in params_return_full()
- [Low] selftests/sched: ignored negative error from probe() in params_return_full()
- [Low] selftests/sched: stale exited TID used on admission error in deadline_bw_test
- [Low] selftests/sched: redundant sched/debug scans and 40s waits in run_p_cases()
--

commit 35a6d94959219214223fe0bdf45f6150f74deca4
Author: Mathieu Desnoyers <[email protected]>

selftests/sched: Test parameter changes in deadline_bw_test

This commit adds 25 test cases to deadline_bw_test covering SCHED_DEADLINE parameter changes, constrained-deadline gap re-entry, and bandwidth retention, and adds post-case bandwidth drain waits in run_p_cases().

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
index dbe0de739e476..58ec444cf1bbf 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
@@ -1455,6 +1477,82 @@ static int params_refused(void)

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int params_refused(void) · line 1546

Quoted 13 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +13 -0
+	err = set_other(t_tid);
+	if (!err)
+		err = set_deadline(t_tid, 60 * NSEC_PER_MSEC, PERIOD);
+	slept = now_ns() - rt_t_slept;
+	if (slept > 15 * NSEC_PER_MSEC) {
+		/* Too late: the 0-lag time may have passed. */
+		ksft_print_msg("T switched back %llums after it slept\n",
+			       (unsigned long long)(slept / NSEC_PER_MSEC));
+		ret = KSFT_SKIP;
+	} else if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		ret = KSFT_FAIL;
+	}

[Severity: Low]
Should err be checked before slept > 15 * NSEC_PER_MSEC here?

Passing T's 0-lag time releases its old 60% bandwidth, so a late switch can only make a zero err inconclusive. A non-zero err (such as -EBUSY on a kernel without the fix) is still a real failure, but checking slept first downgrades it to KSFT_SKIP whenever jitter pushes slept past 15ms.

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int params_refused(void) · line 1550

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +4 -0
+	if (ret == KSFT_PASS && probe(NULL) >= 6) {
+		ksft_print_msg("P has room for two tasks of 60%%\n");
+		ret = KSFT_SKIP;
+	}

[Severity: Low]
What happens if probe(NULL) fails and returns -1 here?

-1 >= 6 is false, so a probe() error falls through as KSFT_PASS without verifying that P lacks room for two 60% tasks. Capturing the return value and handling < 0 (as measured() does) would avoid masking probe failures.

[ ... ]

Quoted 1 line
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
@@ -1867,169 +1966,1833 @@ static void *refill_owner(void *arg)

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int return_asleep_new_params(void) · line 2220

Quoted 9 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +9 -0
+	shrink_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	shrink_t0 = t0;
+	sem_post(&shrink_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}

[Severity: Low]
Can wake_after_deadline_shrunk() operate on a stale TID when set_deadline() fails in shrink_t()?

shrink_t() posts shrink_ready and exits immediately on error without recording an error flag, which autoreaps the thread and releases shrink_tid before pthread_join(). wake_after_deadline_shrunk() then sleeps until 105ms and calls proc_state_of(shrink_tid) and set_constrained(shrink_tid, ...) on the exited TID. The same pattern appears in widen_t()/deadline_widened_asleep(), shorten_t()/shorten_case(), and flip_t()/params_flip_no_gain(); storing err before sem_post() and aborting early (as pr_h() and vic_b() do) would avoid it.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int return_asleep_new_params(void) · line 3092

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +10 -0
+static void *cmix_a(void *arg)
+{
+	int err = set_deadline(0, 15 * NSEC_PER_MSEC, PERIOD);
+
+	if (err) {
+		ksft_print_msg("A refused as a deadline task: %s\n", strerror(-err));
+		cmix_stop = 1;
+		sem_post(&cmix_go);
+		return (void *)1;
+	}

[Severity: Low]
Should constrained_after_job() return KSFT_SKIP instead of KSFT_FAIL when cmix_a() or cmix_b() gets -EBUSY?

Together with the 5% fair server, B (75%) and A (15%) require the full 95% default admission limit. On systems where sched_rt_runtime_us is lower or the fair/ext server reserves more than 5%, set_deadline() returns -EBUSY, which currently fails the test rather than skipping as params_swap_overload() does.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int return_asleep_new_params(void) · line 3446

Quoted 7 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +7 -0
+	rb2_t_locking = 1;
+	if (syscall(SYS_futex, &rb2_pi, FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG,
+		    0, NULL, NULL, 0)) {
+		ksft_print_msg("FUTEX_LOCK_PI: %s\n", strerror(errno));
+		set_other(0);
+		return (void *)1;
+	}

[Severity: Low]
Should reenter_pi_blocked_in_gap() skip on ENOSYS and wake the main thread immediately if FUTEX_LOCK_PI fails?

Unlike the other PI cases, this one bypasses pi_init() and invokes FUTEX_LOCK_PI directly, which returns -ENOSYS when CONFIG_FUTEX_PI is disabled. Because rb2_t() returns without setting rb2_t_locking negative, the main thread stalls for the full 1s wait_for() timeout and returns KSFT_FAIL instead of KSFT_SKIP.

[ ... ]

Quoted 6 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +6 -0
+	while (!rr_stop) {
+		uint64_t t = now_ns(), b = rr_back_at;
+
+		if (b && !rr_t_ran && t > b + 2 * NSEC_PER_MSEC)
+			rr_t_ran = t;
+	}

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int return_asleep_new_params(void) · line 3753

Quoted 3 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +3 -0
+	/* Store it before the switch back. A T given a new period runs at once. */
+	rr_back_at = now_ns();
+	err = set_constrained(rr_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);

[Severity: Low]
Can the 2ms grace window in rr_t() expire while T is still running as SCHED_OTHER, causing a false failure in reenter_runnable_in_gap()?

Both threads share P's single CPU, and T is already runnable as SCHED_OTHER when rr_back_at is published:

reenter_runnable_in_gap()
set_other(rr_t_tid)
rr_back_at = now_ns()
<preempted by rr_t as SCHED_OTHER>
spins for > 2ms (e.g. EEVDF slice or HZ=250/HZ=100 tick)
rr_t_ran = t <-- recorded while SCHED_OTHER
set_constrained(rr_t_tid, ...)

On systems with 4+ CPUs (where the EEVDF base slice exceeds 2ms) or HZ=250/HZ=100 kernels, T can run past b + 2ms before set_constrained() takes effect. Checking sched_getscheduler(0) == SCHED_DEADLINE before recording rr_t_ran would avoid the race.

[ ... ]

Quoted 1 line
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
@@ -5937,6 +7832,144 @@ static int params_waking(void)

[ ... ]

Quoted 6 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +6 -0
+	while (!err && (t = now_ns()) < start + SW_SETTLE + SW_WINDOW) {
+		if (!t0 && t >= start + SW_SETTLE) {
+			t0 = t;
+			cpu0[0] = sw_state[2];
+			cpu0[1] = sw_state[3];
+		}

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int params_waking(void) · line 7958

Quoted 8 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +8 -0
+	t1 = now_ns();
+	used[0] = sw_state[2] - cpu0[0];
+	used[1] = sw_state[3] - cpu0[1];
+	if (err) {
+		ksft_print_msg("a change refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (100000 * (used[0] + used[1]) >= SW_MAX_SHARE * (long long)(t1 - t0)) {

[Severity: Low]
What if the main process stalls past start + SW_SETTLE + SW_WINDOW before any loop iteration sets t0?

The loop exits with t0 still 0, so t1 - t0 becomes total monotonic uptime since boot. That inflates the denominator and lets the test silently pass without measuring the window (and can overflow signed long long if uptime exceeds ~3.4 years). Checking !t0 || t1 <= t0 and skipping or failing would catch this.

[ ... ]

Quoted 13 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +6 -0
@@ -11250,6 +13319,12 @@ static void run_p_cases(void)
 	}
 	for (i = 0; i < N_P_CASES; i++) {
 		const struct p_case *c = &p_cases[i];
+		long long bw0 = total_bw_of(top_cpu(1));
+		long this0[3];
+		int k;
+
+		for (k = 0; k < 3; k++)
+			this0[k] = this_bw_of(top_cpu(k + 1));
 
 		if (ok && make_p()) {
 			remove_p();

[ ... ]

Quoted 24 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +20 -0
@@ -11269,6 +13344,34 @@ static void run_p_cases(void)
 			ret = c->fn();
 		remove_p();
 		server_restore();
+		/*
+		 * A task of the case can keep its bandwidth counted after it
+		 * exits: until its 0-lag time, or until its debt is repaid. Wait
+		 * for that, so that the next case starts from the same total_bw.
+		 * A lower total_bw also ends the wait. Bandwidth lost by a case
+		 * would never come back, and the wait would then cost the whole
+		 * 10s.
+		 */
+		if (bw0 >= 0 &&
+		    wait_for_step(10000, 10 * NSEC_PER_MSEC,
+				  total_bw_of(top_cpu(1)) <= bw0))
+			ksft_print_msg("%s: total_bw %lld after the case, %lld before\n",
+				       c->name, total_bw_of(top_cpu(1)), bw0);
+		/*
+		 * this_bw can stay higher than total_bw shows. A task moved to
+		 * another cpuset while it sleeps leaves its bandwidth in the
+		 * this_bw of its old CPU until it wakes up or dies. Wait for
+		 * the three CPUs that random_mix() checks.
+		 */
+		for (k = 0; k < 3; k++) {

tools/testing/selftests/sched/deadline/deadline_bw_test.c static void run_p_cases(void) · line 13376

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +8 -0
+			int cpu = top_cpu(k + 1);
+
+			if (this0[k] >= 0 &&
+			    wait_for_step(10000, 10 * NSEC_PER_MSEC,
+					  this_bw_of(cpu) <= this0[k]))
+				ksft_print_msg("%s: this_bw of CPU %d %ld after the case, %ld before\n",
+					       c->name, cpu, this_bw_of(cpu), this0[k]);
+		}
 		report(c->name, ret);
 	}

[Severity: Medium]
Does skipping these post-case waits when debugfs is unavailable still leave random_mix() failing after params_swap_overload()?

total_bw_of() and this_bw_of() both return -1 without /sys/kernel/debug/sched/debug, so both wait loops are bypassed completely. params_swap_overload() runs right before random_mix() and exits while its reaped children still carry multi-second 0-lag debt on P's CPU; when random_mix() falls back to admission-only checks without debugfs, probe(cg_p) measures a depressed base_p before the debt drains, and admits_in() fails once the debt expires mid-test.

[Severity: Low]
Can these pre- and post-case sched/debug reads be combined into a single pass and guarded by ok?

Right now run_p_cases() does four separate full scans of /sys/kernel/debug/sched/debug per case even when !ok causes all cases to skip, and each scan walks every thread on every CPU up to top_cpu(1..3). After each case, the four sequential 10s wait loops can also stall up to 40s (4,000 full scans) on a leaking case, risking the 600s kselftest timeout; polling all four values in one pass inside a single wait loop would avoid both.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=33
#51 lore raw

PATCH v14 34/39 sched/deadline: Count a task that departs while a rebuild walks the tasks

In reply to Mathieu Desnoyers

dl_rebuild_rd_accounting() rebuilds the root domains' accounting in two steps. First, dl_clear_root_domains() clears the root domains. Then it puts back the bandwidth of the departed tasks, which left SCHED_DEADLINE or died before their 0-lag time. Second, the walk of the task list counts each deadline task.

A task can leave the class after the clear, before the walk reaches
it: priority inheritance can deboost it. The walk then finds a task out of the class, and skips it. Neither step counts its bandwidth. The comment above dl_departed_list lists this as a known gap.

In this example, the deadline task W waits with a timeout on an rt_mutex that T holds. T was a deadline task too. While W boosted it, sched_setattr() switched T to SCHED_OTHER. The boost keeps T in the class, with its bandwidth. W runs on CPU 1. CPU 0 rebuilds the accounting, for example after a write to cpuset.cpus.partition.

CPU 0 CPU 1
----- -----
dl_rebuild_rd_accounting()
dl_clear_root_domains()
clear total_bw
put back the departed tasks
W times out: remove_waiter()
rt_mutex_setprio(T)
switched_from_dl(T)
dl_task_depart(T)
T joins the departed list
walk of the task list reaches T
T is out of the class: skip it

total_bw then misses the bandwidth of T until its 0-lag time. Meanwhile, sched_setattr() can admit tasks beyond the capacity of the root domain.

Fix this by counting such a task in dl_task_depart(), as the walk would have. dl_bw_move_blocked() already tells whether the walk has yet to reach the task. The new dl_task_count_cpu() picks the CPU as the walk does in dl_task_rebuild_cpu(). But it does not ask the cpuset for the CPUs of the task. That needs cpuset_mutex, and dl_task_depart() runs under the rq lock. If no CPU of the mask of the task is active, leave the task out. A rebuild drops a bandwidth in the same way when the CPU recorded with it is no longer active.

A task that dies in the same window departs too. The walk counted it from the departed list, unless release_task() had taken it off the task list. dl_task_depart() now counts it in both cases.

This was found by reading the code, and by a Spin model of the accounting. The pi_deboost_during_rebuild case of deadline_bw_test races the timeout with the rebuild. "selftests/sched: Test PI against hotplug and rebuilds in deadline_bw_test", later in this series, adds the case. The runs used v13 of this series, which had an earlier version of this fix. The case failed in 35 of 43 runs without the fix, and passed in 35 of 35 with it.

Fixes f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
---
 kernel/sched/deadline.c | 77 ++++++++++++++++++++++++++++++++++-------
 1 file changed, 65 insertions(+), 12 deletions(-)
kernel/sched/deadline.c +65 -12
index 871507b37759..02c6e2c20027 100644
@@ -223,6 +223,8 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
 	       cap_scale(dl_b->bw, cap) < dl_b->total_bw - old_bw + new_bw;
 }
 
+static unsigned int dl_task_count_cpu(struct task_struct *p);
+
 /*
  * A task that leaves SCHED_DEADLINE, or dies, before its 0-lag time keeps
  * its bandwidth in total_bw until that time. Then the inactive timer
@@ -253,12 +255,14 @@ __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw)
  * harmless.
  *
  * A rebuild drops the bandwidth when the CPU recorded is no longer
- * active. It also drops the bandwidth of a task that dies while the
- * rebuild runs. The walk of the task list does not find that task, and
- * it was not dead yet when the list was put back. The same happens to a
- * task that priority inheritance deboosts while the rebuild runs. It was
- * in the class when the list was put back, and out of it when the walk
- * reaches it.
+ * active. It also drops the bandwidth of a task that release_task()
+ * took off the task list, if its last schedule comes after the walk.
+ * The walk does not find that task, and it was not on the departed
+ * list when the list was put back.
+ *
+ * A task can also depart after the list was put back, and before the
+ * walk reaches it. Priority inheritance can deboost it, or it can die.
+ * dl_task_depart() then counts it, as the walk would have.
  *
  * dl_departed_lock protects the list and both counts. Take it with
  * interrupts disabled, under the task's rq lock or pi_lock or in the
@@ -376,6 +380,23 @@ bool dl_task_holds_bw(struct task_struct *p)
 	return dl_se_holds_bw(&p->dl);
 }
 
+/*
+ * Add the bandwidth of @p to the root domain of @cpu, for a task that no
+ * root domain counts now. Record @cpu, and date the record with the
+ * current dl_bw_gen. The caller holds dl_departed_lock.
+ */
+static void dl_task_count_bw(struct task_struct *p, int cpu)
+{
+	struct dl_bw *dl_b = dl_bw_of(cpu);
+
+	lockdep_assert_held(&dl_departed_lock);
+	raw_spin_lock(&dl_b->lock);
+	__dl_add(dl_b, p->dl.dl_bw, dl_bw_cpus(cpu));
+	raw_spin_unlock(&dl_b->lock);
+	dl_record_bw_cpu(&p->dl, cpu);
+	p->dl.dl_bw_gen = dl_bw_gen;
+}
+
 /*
  * Put @p on dl_departed_list. The root domain of the CPU recorded with it
  * keeps its bandwidth. @p leaves SCHED_DEADLINE, or dies, before its
@@ -400,6 +421,20 @@ static void dl_task_depart(struct task_struct *p)
 	if (dl_se->dl_bw_gen == dl_bw_gen && !dl_bw_rebuilding() && cpu_active(cpu) &&
 	    cpu_rq(cpu)->rd == cpu_rq(dl_se->dl_bw_cpu)->rd)
 		dl_record_bw_cpu(dl_se, cpu);
+	/*
+	 * dl_clear_root_domains() counted the departed tasks, and the walk
+	 * of the task list counts the deadline tasks. A task that departs
+	 * after the clear, before the walk reaches it, would be counted by
+	 * neither. Count it here, on the CPU the walk would have picked. If
+	 * no CPU of its mask is active, leave it out. While the sched domains
+	 * are rebuilt, the clear is still ahead, and finds the task on the
+	 * list.
+	 */
+	if (dl_bw_move_blocked(p) && !dl_bw_rebuilding()) {
+		cpu = dl_task_count_cpu(p);
+		if (cpu < nr_cpu_ids)
+			dl_task_count_bw(p, cpu);
+	}
 	list_add(&dl_se->dl_departed_node, &dl_departed_list);
 }
 
@@ -4404,13 +4439,16 @@ static void dl_get_task_effective_cpus(struct task_struct *p, struct cpumask *cp
  * throttled task and its bandwidth on any active CPU. The task runs there
  * until it blocks. Inside a rebuild, that move leaves the record on the
  * CPU that went offline.
+ *
+ * With @ask_cpuset, ask the cpuset for the CPUs of @p if no CPU of its
+ * mask is active. That needs cpuset_mutex.
  */
-static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
+static unsigned int __dl_task_rebuild_cpu(struct task_struct *p, bool ask_cpuset)
 {
 	struct cpumask *msk = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
 	/*
 	 * Read the record once. The last schedule of a dead task clears it
-	 * under its rq lock, and the caller holds only the pi_lock.
+	 * under its rq lock, which some callers do not hold.
 	 */
 	int recorded = READ_ONCE(p->dl.dl_bw_cpu);
 	unsigned int cpu;
@@ -4427,7 +4465,7 @@ static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
 	if (cpu_active(cpu) && task_on_rq_queued(p) &&
 	    (cpu == recorded || !cpumask_test_cpu(cpu, &p->cpus_mask)))
 		return cpu;
-	if (cpumask_empty(msk)) {
+	if (cpumask_empty(msk) && ask_cpuset) {
 		dl_get_task_effective_cpus(p, msk);
 		cpumask_and(msk, msk, cpu_active_mask);
 	}
@@ -4460,6 +4498,22 @@ static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
 	return cpumask_first(msk);
 }
 
+static unsigned int dl_task_rebuild_cpu(struct task_struct *p)
+{
+	return __dl_task_rebuild_cpu(p, true);
+}
+
+/*
+ * Return the CPU on which the walk of the task list would count @p, for a
+ * task counted outside the walk. Unlike the walk, do not ask the cpuset.
+ * Return nr_cpu_ids if no CPU of the mask of @p is active. The caller must
+ * disable interrupts.
+ */
+static unsigned int dl_task_count_cpu(struct task_struct *p)
+{
+	return __dl_task_rebuild_cpu(p, false);
+}
+
 /* From dl_rebuild_rd_accounting(), under the locks it asserts. */
 void dl_add_task_root_domain(struct task_struct *p)
 {
@@ -4502,9 +4556,8 @@ void dl_add_task_root_domain(struct task_struct *p)
 	 * dl_clear_root_domains() put it back as a departed task, and
 	 * priority inheritance boosted it into the class since. Or it died
 	 * since the rebuild started, and dl_task_release_bw() released its
-	 * bandwidth. A task that died since with its 0-lag time ahead is on
-	 * the departed list. Count it in the root domain of the CPU
-	 * recorded, if that CPU is active.
+	 * bandwidth. Or it departed before the walk reached it, and
+	 * dl_task_depart() counted it.
 	 */
 	if (p->dl.dl_bw_gen == dl_bw_gen)
 		goto unlock;
Signature · 1 line
2.47.3
#52 lore raw

PATCH v14 35/39 sched/deadline: Count again a departed task that a boost brings back

In reply to Mathieu Desnoyers

A task that leaves SCHED_DEADLINE before its 0-lag time is a departed task. Its root domain keeps its bandwidth until then, and the task waits on dl_departed_list. A rebuild of the root domains' accounting puts this bandwidth back in the root domain of the CPU recorded with it. If that CPU is no longer active, the rebuild drops the bandwidth. A CPU that goes offline is in the default root domain by then, so the root domain that counted the task cannot be found. dl_bw_gen then keeps the release of the task from removing anything.

But priority inheritance can bring such a task back into the class. Here a partition root has CPUs X and Y:

1. A deadline task T holds an rt_mutex, and sleeps on X. X is the CPU recorded with its bandwidth.
2. sched_setattr() makes T a SCHED_OTHER task, before its 0-lag time. T goes on the departed list.
3. T wakes up on Y, then sleeps there. The record stays X.
4. X goes offline. The rebuild that follows drops the bandwidth of T.
5. A deadline task blocks on the rt_mutex. It boosts T back into the class, before the 0-lag time of T.

switched_to_dl() takes T off the departed list. this_bw of Y counts T again, but no root domain counts it in total_bw. Until the deboost, sched_setattr() can admit tasks beyond the capacity of the root domain.

Fix this in dl_task_undepart(). If a rebuild dropped the bandwidth, count it again on the CPU that the walk of the task list would pick (dl_task_count_cpu()). Do not use the CPU of the task. The task can sleep on a CPU that went offline, or on one that its mask no longer holds. If no CPU of its mask is active, the move of the task to an active CPU counts it (dl_task_move_bw()).

dl_task_undepart() leaves the task to the walk of the task list after a rebuild, if the walk has not reached it yet (dl_bw_move_blocked()). But the walk counts only the tasks in the class, so it can pass a departed task. The walk marks in dl_bw_skip_gen the tasks it leaves out, and dl_bw_move_blocked() lets them through. Mark in the same way the departed tasks that dl_clear_root_domains() and dl_task_depart() leave out.

This was found by reading the code. The pi_departed_offline_boost case of deadline_bw_test shows the bug. "selftests/sched: Test PI against hotplug and rebuilds in deadline_bw_test", later in this series, adds the case. The runs used v13 of this series, which had an earlier version of this fix. The case failed in 33 of 33 runs without the fix, and passed in 25 of 25 with it.

Fixes f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
---
 include/linux/sched.h   |  8 ++++----
 kernel/sched/deadline.c | 38 +++++++++++++++++++++++++++++++-------
 2 files changed, 35 insertions(+), 11 deletions(-)
include/linux/sched.h +4 -4
index b32421cd0107..e27d341ca763 100644
@@ -762,10 +762,10 @@ struct sched_dl_entity {
 	 * @dl_bw_gen is the value of dl_bw_gen when the bandwidth was last
 	 * counted. If a rebuild dropped it since, there is nothing to remove.
 	 *
-	 * @dl_bw_skip_gen is the value of dl_bw_gen when the walk of the
-	 * task list after a rebuild left the task out: no CPU of it was
-	 * active. A move of the task then counts the bandwidth, even before
-	 * the walk ends.
+	 * @dl_bw_skip_gen is the value of dl_bw_gen when a rebuild of the
+	 * accounting left the task out. Before the walk of the task list
+	 * ends, a move of the task can then count the bandwidth. So can a
+	 * boost of a departed task back into the class.
 	 *
 	 * @dl_bw_resv_cpu is a CPU of the root domain where a cpuset attach
 	 * in progress reserved room for the bandwidth, or -1.
kernel/sched/deadline.c +31 -7
index 02c6e2c20027..f2429672358c 100644
@@ -249,7 +249,7 @@ static unsigned int dl_task_count_cpu(struct task_struct *p);
  *    it back.
  *  - Older: an earlier rebuild dropped it. A task on the departed list
  *    stays out, and its release removes nothing. A task that is in the
- *    class is counted again.
+ *    class, or that a boost brings back into it, is counted again.
  *
  * Only equalities are compared, so the wrap of the counter is
  * harmless.
@@ -305,8 +305,8 @@ static inline bool dl_bw_rebuilding(void)
  * Return true if the bandwidth of @p must not move now. Either the sched
  * domains are rebuilt, or the walk of the task list that follows has not
  * reached @p yet. The walk then counts @p. A move must not count it
- * first. A task the walk left out, with no active CPU, can move: no one
- * else counts it.
+ * first. A task that the rebuild left out can move, or come back into
+ * the class by a boost. No one else counts it. dl_bw_skip_gen marks it.
  *
  * The answer is exact under dl_departed_lock. Without it, the answer is a
  * hint: dl_task_move_bw() tests again under the lock.
@@ -434,6 +434,8 @@ static void dl_task_depart(struct task_struct *p)
 		cpu = dl_task_count_cpu(p);
 		if (cpu < nr_cpu_ids)
 			dl_task_count_bw(p, cpu);
+		else
+			WRITE_ONCE(dl_se->dl_bw_skip_gen, dl_bw_gen);
 	}
 	list_add(&dl_se->dl_departed_node, &dl_departed_list);
 }
@@ -442,6 +444,12 @@ static void dl_task_depart(struct task_struct *p)
  * Take @p off dl_departed_list. @p comes back to the deadline class, and
  * its bandwidth is that of a deadline task again. The caller holds the rq
  * lock of @p.
+ *
+ * A rebuild may have dropped the bandwidth while @p was departed. No root
+ * domain counts it then, but this_bw of its CPU does again once @p is
+ * back. Count it on the CPU the walk of the task list would pick. Leave it
+ * to the walk if the walk has not reached @p yet. Leave it to the move of
+ * @p to an active CPU if no CPU of its mask is active.
  */
 static void dl_task_undepart(struct task_struct *p)
 {
@@ -452,6 +460,12 @@ static void dl_task_undepart(struct task_struct *p)
 		return;
 	guard(raw_spinlock)(&dl_departed_lock);
 	list_del_init(&dl_se->dl_departed_node);
+	if (dl_se->dl_bw_gen != dl_bw_gen && !dl_bw_move_blocked(p)) {
+		unsigned int cpu = dl_task_count_cpu(p);
+
+		if (cpu < nr_cpu_ids)
+			dl_task_count_bw(p, cpu);
+	}
 }
 
 /*
@@ -4767,16 +4781,17 @@ void dl_clear_root_domains(void)
 		 * (dl_task_release_bw()).
 		 */
 		if (dl_se->dl_bw_gen != dl_bw_gen - 1)
-			continue;
+			goto left_out;
 		/*
 		 * Drop the bandwidth of a task whose CPU is inactive. A CPU
 		 * that goes offline is in the default root domain by then.
 		 * The root domain that counted the task cannot be found
 		 * from the recorded number. The release then removes
-		 * nothing, and no later rebuild restores it.
+		 * nothing. A boost of the task back into the class counts
+		 * it again (dl_task_undepart()).
 		 */
 		if (cpu < 0 || !cpu_active(cpu))
-			continue;
+			goto left_out;
 		dl_b = dl_bw_of(cpu);
 		raw_spin_lock(&dl_b->lock);
 		__dl_add(dl_b, dl_se->dl_bw, dl_bw_cpus(cpu));
@@ -4787,6 +4802,14 @@ void dl_clear_root_domains(void)
 		 */
 		dl_record_bw_cpu(dl_se, cpu);
 		dl_se->dl_bw_gen = dl_bw_gen;
+		continue;
+left_out:
+		/*
+		 * The walk counts only the tasks in the class. It can pass
+		 * this task before a boost brings it back. Mark the task, so
+		 * that dl_bw_move_blocked() lets the boost count it at once.
+		 */
+		WRITE_ONCE(dl_se->dl_bw_skip_gen, dl_bw_gen);
 	}
 }
 
@@ -4884,7 +4907,8 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 	 * meanwhile, its next wakeup or migration there first moves the
 	 * bandwidth and the record, as for any deadline task. A rebuild while
 	 * it is boosted counts it like any deadline task, and records the CPU
-	 * it picks.
+	 * it picks. If a rebuild dropped the bandwidth meanwhile,
+	 * dl_task_undepart() counts it again, and records the CPU it picks.
 	 */
 	dl_task_undepart(p);
 
Signature · 1 line
2.47.3
#53 lore raw

Re: [PATCH v14 35/39] sched/deadline: Count again a departed task that a boost brings back

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: data race and missing ordering on dl_bw_gen and dl_bw_cpu --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: data race and missing ordering on dl_bw_gen and dl_bw_cpu
--

commit 8b5f6b6125146e7ac12829f073f80ce655afb418
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Count again a departed task that a boost brings back

This commit updates dl_task_undepart() to recount a departed task's bandwidth when priority inheritance brings it back into SCHED_DEADLINE after a root domain rebuild dropped it. It also marks skipped departed tasks in dl_bw_skip_gen so dl_bw_move_blocked() allows the boost to recount them before the rebuild walk finishes.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 02c6e2c200279..f2429672358c0 100644

[ ... ]

Quoted 4 lines
kernel/sched/deadline.c +0 -0
@@ -4787,6 +4802,14 @@ void dl_clear_root_domains(void)
 		 */
 		dl_record_bw_cpu(dl_se, cpu);
 		dl_se->dl_bw_gen = dl_bw_gen;

kernel/sched/deadline.c void dl_clear_root_domains(void) · line 4814

Quoted 10 lines
kernel/sched/deadline.c +8 -0
+		continue;
+left_out:
+		/*
+		 * The walk counts only the tasks in the class. It can pass
+		 * this task before a boost brings it back. Mark the task, so
+		 * that dl_bw_move_blocked() lets the boost count it at once.
+		 */
+		WRITE_ONCE(dl_se->dl_bw_skip_gen, dl_bw_gen);
 	}
 }

[Severity: Medium]
Can the plain stores to dl_bw_gen and the lockless load order in dl_task_bw_elsewhere() and dl_task_bw_rd() race with concurrent writers?

dl_clear_root_domains(), dl_task_count_bw() (now also called from dl_task_undepart()), dl_add_task_root_domain(), and dl_task_move_bw() update dl_bw_cpu and dl_bw_def via dl_record_bw_cpu() and then assign dl_bw_gen with a plain store under dl_departed_lock. Lockless readers such as dl_task_bw_elsewhere() load dl_bw_cpu before reading dl_bw_gen with READ_ONCE(), without holding dl_departed_lock or acquire ordering:

CPU0 CPU1
---- ----
sched_ttwu_pending()
rq_lock(rq_rd2)
... -> task_woken_dl(rq_rd2, p)
dl_task_bw_elsewhere(p, cpu_rd2)
bw_cpu = READ_ONCE(dl_bw_cpu) (stale CPU in rd2, gen G-1)
dl_add_task_root_domain(p)
lock(pi_lock, dl_departed_lock)
dl_record_bw_cpu(&p->dl, cpu_rd1)
p->dl.dl_bw_gen = G
unlock(...)

                                          READ_ONCE(dl_bw_gen) == G
                                          rd(bw_cpu) == rd(cpu_rd2)
                                          return false  <-- skips move

Besides the data race on dl_bw_gen, CPU1 pairs the stale bw_cpu in rd2 with the new generation G and skips dl_task_move_bw(). That leaves p running in rd2 while its bandwidth is accounted in rd1, allowing temporary bandwidth over-admission or spurious admission failures until a later migration or rebuild.

Similarly, dl_task_bw_rd() runs under p->pi_lock without dl_departed_lock and reads dl_bw_cpu before dl_bw_gen and dl_bw_def, so it can race with dl_task_move_bw() or dl_task_count_bw() to return a stale root domain or pair an old dl_bw_cpu with a new dl_bw_def.

Publishing dl_bw_gen with smp_store_release() after dl_record_bw_cpu() and loading dl_bw_gen with smp_load_acquire() before dl_bw_cpu (or rechecking under a consistent ordering protocol) would prevent both the data race and the mismatched reads.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=35
#54 lore raw

PATCH v14 36/39 sched/deadline: Keep a reaped deadline task in a rebuild

In reply to Mathieu Desnoyers

A rebuild of the root domains' accounting counts tasks from two places:
dl_departed_list, and the task list. The walk of the task list counts a dying deadline task until its last schedule. That schedule releases the bandwidth, or puts the task on dl_departed_list until its 0-lag time.

But release_task() can take a task off the task list before its last schedule. A thread other than the group leader reaps itself in exit_notify(). A parent can reap a zombie child while the child still runs. A rebuild in that window finds the task in neither place, and drops its bandwidth. total_bw then misses it until the last schedule, or until the 0-lag time if that is later. Meanwhile, sched_setattr() would admit tasks beyond the capacity of the root domain.

Fix this by putting such a task on dl_departed_list from release_task(), in the new dl_task_unhash(). It runs under tasklist_lock, before the task leaves the task list, so no walk runs in between. A rebuild then counts the task with the departed tasks. Its last schedule releases the bandwidth and takes it off the list, or leaves both to the inactive timer.

dl_task_unhash() reads dl_bw under the rq lock of the task. __sched_setscheduler() admits under that lock, and can still admit the task at this point. It tests exit_state, which the task sets without that lock. So release_task() now takes the rq lock of each task it reaps.

A reap after dl_clear_root_domains() and before the walk is covered by "sched/deadline: Count a task that departs while a rebuild walks the tasks". dl_task_depart() counts the task then, as the walk would have.

A boost back into the class takes a task off the list, in dl_task_undepart(). Keep a task that has exited on it: it may be off the task list already.

A task on the list can then still run in the class. This needs four more changes:

- dl_clear_root_domains() drops the bandwidth of a task on the list whose recorded CPU is inactive. A task that still runs in the class can run on another CPU than the one recorded. Count it on the CPU that the walk would pick.
- If no CPU of its mask is active, the clear leaves the task out. If the walk finds the task, dl_add_task_root_domain() counts it: the walk can ask the cpuset.
- If the 0-lag time is ahead, the last schedule of the task calls dl_task_depart() again. Update the CPU recorded there, even for a task already on the list.
- A boost can bring an exited task back into the class after an earlier rebuild dropped its bandwidth. During a rebuild of the sched domains, dl_task_undepart() cannot count it yet, and the walk skips a task on the list. So dl_task_undepart() asks the clear that ends the rebuild to count the task, through dl_bw_skip_gen.

A Spin model of the accounting found this case. It was not reproduced:
the window from release_task() to the last schedule is short. With this fix and the one named above, the model finds no error for two tasks and one root domain.

Fixes f9a25f776d78 ("cpusets: Rebuild root domain deadline accounting information")
---
 include/linux/sched.h          |   4 +-
 include/linux/sched/deadline.h |   1 +
 kernel/exit.c                  |   2 +
 kernel/sched/deadline.c        | 132 ++++++++++++++++++++++++---------
 4 files changed, 104 insertions(+), 35 deletions(-)
include/linux/sched.h +3 -1
index e27d341ca763..d2531a4e3dba 100644
@@ -765,7 +765,9 @@ struct sched_dl_entity {
 	 * @dl_bw_skip_gen is the value of dl_bw_gen when a rebuild of the
 	 * accounting left the task out. Before the walk of the task list
 	 * ends, a move of the task can then count the bandwidth. So can a
-	 * boost of a departed task back into the class.
+	 * boost of a departed task back into the class. dl_task_undepart()
+	 * can also set it one ahead, to ask the next dl_clear_root_domains()
+	 * to count the task.
 	 *
 	 * @dl_bw_resv_cpu is a CPU of the root domain where a cpuset attach
 	 * in progress reserved room for the bandwidth, or -1.
include/linux/sched/deadline.h +1 -0
index deddfca67ec2..1297a7a8d3fd 100644
@@ -36,6 +36,7 @@ extern void dl_clear_root_domains(void);
 extern void dl_bw_rebuild_begin(void);
 extern void dl_rebuild_rd_accounting(void);
 extern bool dl_task_holds_bw(struct task_struct *p);
+extern void dl_task_unhash(struct task_struct *p);
 /*
  * Keep a rebuild of the root domains' accounting and an admission of
  * bandwidth from running at the same time. With cpusets, cpuset_mutex
kernel/exit.c +2 -0
index d5e7bc2af804..1656b4d1b661 100644
@@ -13,6 +13,7 @@
 #include <linux/sched/task.h>
 #include <linux/sched/task_stack.h>
 #include <linux/sched/cputime.h>
+#include <linux/sched/deadline.h>
 #include <linux/interrupt.h>
 #include <linux/module.h>
 #include <linux/capability.h>
@@ -264,6 +265,7 @@ void release_task(struct task_struct *p)
 
 	write_lock_irq(&tasklist_lock);
 	ptrace_release_task(p);
+	dl_task_unhash(p);
 	__exit_signal(&post, p);
 
 	/*
kernel/sched/deadline.c +98 -34

209 lines not on this page · raw message

Signature · 1 line
2.47.3
#55 lore raw

Re: [PATCH v14 36/39] sched/deadline: Keep a reaped deadline task in a rebuild

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] sched/deadline: unconditional task_rq_lock() in release_task() regresses exit - [Medium]…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] sched/deadline: unconditional task_rq_lock() in release_task() regresses exit
- [Medium] sched/deadline: rebuilds drop live dl_departed_list tasks with older dl_bw_gen
- [Medium] sched/deadline: rebuilds drop 0-lag bw on TASK_DEAD/deboost race before depart
- [Medium] sched/deadline: dl_clear_root_domains() skips task/CPU checks on active CPU
--

commit f94214ebaf6d381e037df3c660707d6ae2d886b2
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Keep a reaped deadline task in a rebuild

This commit adds dl_task_unhash() to release_task() so a reaped deadline task is placed on dl_departed_list before leaving the task list, keeping its bandwidth accounted across root-domain rebuilds until its last schedule or 0-lag time. It also keeps exited tasks on dl_departed_list when boosted back into SCHED_DEADLINE and updates dl_clear_root_domains() and dl_add_task_root_domain() to account for live tasks on that list.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index f2429672358c0..1eba22b9010bd 100644

[ ... ]

Quoted 17 lines
kernel/sched/deadline.c +13 -0
@@ -440,6 +444,30 @@ static void dl_task_depart(struct task_struct *p)
 	list_add(&dl_se->dl_departed_node, &dl_departed_list);
 }
 
+/*
+ * Put @p on dl_departed_list if it is a deadline task with a bandwidth.
+ * release_task() calls this before it takes @p off the task list, so
+ * that a rebuild still counts @p until its last schedule. That schedule,
+ * or the inactive timer after it, takes @p off the list. The caller holds
+ * tasklist_lock for writing: no walk of the task list runs meanwhile.
+ */
+void dl_task_unhash(struct task_struct *p)
+{
+	struct rq_flags rf;
+	struct rq *rq;
+
+	lockdep_assert_held_write(&tasklist_lock);

kernel/sched/deadline.c static void dl_task_depart(struct task_struct *p) · line 469

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	/*
+	 * Test dl_bw under the rq lock. __sched_setscheduler() admits under
+	 * that lock, and can still admit @p here: @p sets exit_state without
+	 * that lock.
+	 */
+	rq = task_rq_lock(p, &rf);
+	if (dl_task(p) && dl_task_holds_bw(p))
+		dl_task_depart(p);
+	task_rq_unlock(rq, p, &rf);
+}

[Severity: High]
Does taking task_rq_lock() unconditionally here regress exit scalability when SCHED_DEADLINE is not in use?

release_task() calls dl_task_unhash() on every reaped process and thread while holding the global tasklist_lock for writing. When a parent reaps a child that last ran on another CPU, acquiring p->pi_lock and the remote rq->__lock under tasklist_lock bounces the runqueue lock cacheline across CPUs, injects contention onto remote CPUs, and extends tasklist_lock hold time for concurrent fork, exit, wait, and /proc walks.

Elsewhere in kernel/sched/deadline.c (such as dl_rebuild_rd_accounting()), work is skipped when dl_nr_bw_tasks is zero. Could dl_task_unhash() avoid task_rq_lock() on the common non-deadline fast path by gating on dl_nr_bw_tasks together with in-flight deadline admissions?

[ ... ]

Quoted 11 lines
kernel/sched/deadline.c +0 -2
@@ -4576,19 +4617,20 @@ void dl_add_task_root_domain(struct task_struct *p)
 	if (p->dl.dl_bw_gen == dl_bw_gen)
 		goto unlock;
 	if (!list_empty(&p->dl.dl_departed_node)) {
-		int recorded = p->dl.dl_bw_cpu;
-
 		/*
 		 * The walk also finds a dead task that departed before an
 		 * earlier rebuild, if it is not reaped yet. If that rebuild
 		 * dropped its bandwidth, dl_clear_root_domains() skipped it,
 		 * and its release removes nothing. Skip it here too.

kernel/sched/deadline.c void dl_add_task_root_domain(struct task_struct *p) · line 4633

Quoted 10 lines
kernel/sched/deadline.c +7 -1
+		 *
+		 * The clear counted the other tasks on the list, or dropped a
+		 * dead task whose CPU is inactive. It left out a task in the
+		 * class with no active CPU in its mask, since it cannot ask
+		 * the cpuset. Count that task here.
 		 */
-		if (p->dl.dl_bw_gen != dl_bw_gen - 1)
+		if (p->dl.dl_bw_gen != dl_bw_gen - 1 || cpu >= nr_cpu_ids ||
+		    READ_ONCE(p->__state) == TASK_DEAD)
 			goto unlock;

[Severity: Medium]
Can this generation check drop the bandwidth of a live task on dl_departed_list whose dl_bw_gen is older than dl_bw_gen - 1?

Suppose an exited departed task had its bandwidth dropped by rebuild G + 1 (leaving p->dl.dl_bw_gen at G), and a boost brings it back into SCHED_DEADLINE during rebuild G + 2 so dl_task_undepart() keeps it on dl_departed_list and sets dl_bw_skip_gen to G + 2. If no CPU in p->cpus_mask is active, dl_clear_root_domains() leaves it out with dl_bw_gen still G, and when dl_add_task_root_domain() later finds an active CPU via the cpuset, p->dl.dl_bw_gen != dl_bw_gen - 1 skips it and leaves total_bw undercounted.

dl_clear_root_domains() has the same problem across consecutive rebuilds:
if a live reaped or boosted task on dl_departed_list is left out by rebuild G + 1 for lack of an active CPU in its mask, rebuild G + 2 skips it at dl_bw_gen != dl_bw_gen - 1 && dl_bw_skip_gen != dl_bw_gen.

Similarly, if an exited departed task is boosted back outside dl_bw_rebuilding() while dl_task_count_cpu() finds no active CPU, dl_task_undepart() does not set dl_bw_skip_gen for the next rebuild, so the next rebuild also drops it.

Checking for live in-class tasks (dl_task(p) && READ_ONCE(p->__state) != TASK_DEAD) before skipping older generations in dl_clear_root_domains() and dl_add_task_root_domain() would cover these cases.

[ ... ]

Quoted 30 lines
kernel/sched/deadline.c +15 -8
@@ -4778,20 +4821,40 @@ void dl_clear_root_domains(void)
 		/*
 		 * Skip bandwidth that an earlier rebuild dropped. It is not
 		 * counted now, and its release removes nothing
-		 * (dl_task_release_bw()).
+		 * (dl_task_release_bw()). Count it anyway if
+		 * dl_task_undepart() asked for it through dl_bw_skip_gen: a
+		 * boost brought an exited task back into the class.
 		 */
-		if (dl_se->dl_bw_gen != dl_bw_gen - 1)
+		if (dl_se->dl_bw_gen != dl_bw_gen - 1 &&
+		    dl_se->dl_bw_skip_gen != dl_bw_gen)
+			goto left_out;
+		if (cpu < 0)
 			goto left_out;
 		/*
-		 * Drop the bandwidth of a task whose CPU is inactive. A CPU
-		 * that goes offline is in the default root domain by then.
-		 * The root domain that counted the task cannot be found
-		 * from the recorded number. The release then removes
-		 * nothing. A boost of the task back into the class counts
-		 * it again (dl_task_undepart()).
+		 * Drop the bandwidth of a departed task whose CPU is inactive.
+		 * A CPU that goes offline is in the default root domain by
+		 * then. The root domain that counted the task cannot be found
+		 * from the recorded number. The release then removes nothing.
+		 * A boost of the task back into the class counts it again
+		 * (dl_task_undepart()).
+		 *
+		 * A task on the list can also still run in the class. It is a

kernel/sched/deadline.c void dl_clear_root_domains(void) · line 4849

Quoted 10 lines
kernel/sched/deadline.c +7 -2
+		 * reaped task before its last schedule, or an exited task that
+		 * a boost brought back. The walk leaves it to the clear. Count
+		 * it on the CPU the walk would pick. This reads the task
+		 * without its locks, so the CPU can be wrong. The bandwidth
+		 * then stays in that root domain until the release, or the
+		 * next rebuild.
 		 */
-		if (cpu < 0 || !cpu_active(cpu))
-			goto left_out;
+		if (!cpu_active(cpu)) {

[Severity: Medium]
When the recorded dl_bw_cpu is still active, can dl_clear_root_domains() charge a live task on dl_departed_list to the wrong root domain?

Because dl_task_count_cpu(p) is only called inside if (!cpu_active(cpu)), a reaped deadline task put on dl_departed_list with dl_bw_cpu = 0 that migrates to CPU1 before a cpuset partition splits {0, 1} into two root domains still has cpu_active(0) true. dl_clear_root_domains() then charges its bandwidth to CPU0's root domain instead of CPU1's, over-accounting one root domain and under-accounting the other until inactive_task_timer() fires.

The same mismatch happens when an exited departed task with dl_bw_skip_gen == dl_bw_gen is boosted on CPU1 while its stale dl_bw_cpu is active in another root domain.

If that exited task is also deboosted before dl_clear_root_domains() runs, dl_task_depart() returns early without clearing dl_bw_skip_gen, and skipping the !dl_task(p) / TASK_DEAD check when cpu_active(cpu) is true resurrects its dropped bandwidth for the rest of its 0-lag period.

kernel/sched/deadline.c void dl_clear_root_domains(void) · line 4857

Quoted 8 lines
kernel/sched/deadline.c +8 -0
+			struct task_struct *p = dl_task_of(dl_se);
+
+			if (!dl_task(p) || READ_ONCE(p->__state) == TASK_DEAD)
+				goto left_out;
+			cpu = dl_task_count_cpu(p);
+			if (cpu >= nr_cpu_ids)
+				goto left_out;
+		}

[Severity: Medium]
Can this check drop a task's 0-lag bandwidth if a rebuild races between do_task_dead() setting TASK_DEAD and task_non_contending() calling dl_task_depart()?

CPU0 (rebuild) CPU2 (task p, dl_bw_cpu = 1)

                                  release_task() -> dl_task_unhash()
                                  /* on dl_departed_list, moves to CPU2 */
                                  do_task_dead()
                                    set_special_state(TASK_DEAD)

/* CPU1 goes offline */
dl_clear_root_domains()
!cpu_active(1)
p->__state == TASK_DEAD
goto left_out <-- bw dropped

                                    __schedule() -> dequeue_task_dl()
                                      task_non_contending()
                                        dl_task_depart(p)
                                          !list_empty -> returns early

Once dl_clear_root_domains() leaves the task out with a stale dl_bw_gen, dl_task_depart() on active CPU2 sees !list_empty(&dl_se->dl_departed_node) and returns without updating dl_bw_cpu or recounting the bandwidth, leaving CPU2's root domain undercounted for the entire 0-lag interval.

A symmetric race happens when rt_mutex_setprio() updates p->prio out of SCHED_DEADLINE before switched_from_dl() calls dl_task_depart(), and dl_add_task_root_domain() has the same TASK_DEAD check for a task on dl_departed_list that has not yet reached its last schedule.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=36
#56 lore raw

PATCH v14 37/39 sched/deadline: Warn when a runqueue keeps the bandwidth of a task

In reply to Mathieu Desnoyers

The this_bw of a runqueue counts the bandwidth of each task whose dl_bw_oncpu is set. add_rq_bw() sets the flag and sub_rq_bw() clears it. Two states would leave a bandwidth in this_bw for ever:

- A task which left the deadline class still has its flag set, and moves to another CPU. Only the deadline class takes the bandwidth off the old runqueue: dequeue_task_dl() for a queued task, and migrate_task_rq_dl() for a waking one. So nothing takes it off.
- task_non_contending() or inactive_task_timer() releases the bandwidth of a task while its flag is still set. They then call __dl_clear_params(), which clears both the flag and dl_bw. After that, nothing can take the bandwidth off the runqueue.

Without a check, a test sees such a leak only later, as a this_bw which does not return to its starting value. It cannot tell which path leaked.

Warn about the first state in set_task_cpu(). Warn about the second in task_non_contending() and inactive_task_timer(), before they call __dl_clear_params(). No warning fires in the selftests of this series.

A review of the accounting code by an LLM suggested these checks.

---
 kernel/sched/core.c     | 3 +++
 kernel/sched/deadline.c | 4 ++++
 2 files changed, 7 insertions(+)
kernel/sched/core.c +3 -0
index 2700c8e98b0e..879ac7d6cdfd 100644
@@ -3517,6 +3517,9 @@ void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
 	 */
 	WARN_ON_ONCE(!cpu_online(new_cpu));
 
+	/* A task of another class would leave its bandwidth in this_bw. */
+	WARN_ON_ONCE(!dl_task(p) && p->dl.dl_bw_oncpu);
+
 	/*
 	 * Proxy execution can move a blocked task's scheduling context to any
 	 * CPU without moving its migration-disabled execution context. The
kernel/sched/deadline.c +4 -0
index 1eba22b9010b..6243f8df898b 100644
@@ -870,6 +870,8 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 			if (!dl_task || READ_ONCE(p->__state) == TASK_DEAD) {
 				if (dl_task && READ_ONCE(p->__state) == TASK_DEAD)
 					sub_rq_bw(dl_se, &rq->dl);
+				/* No runqueue may still count dl_bw. */
+				WARN_ON_ONCE(dl_se->dl_bw_oncpu);
 				dl_task_release_bw(p);
 				cancel_replenish_timer(dl_se);
 				dl_release_params(dl_se);
@@ -2788,6 +2790,8 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 			dl_se->dl_non_contending = 0;
 		}
 
+		/* No runqueue may still count dl_bw. */
+		WARN_ON_ONCE(dl_se->dl_bw_oncpu);
 		dl_task_release_bw(p);
 		cancel_replenish_timer(dl_se);
 		dl_release_params(dl_se);
Signature · 1 line
2.47.3
#57 lore raw

Re: [PATCH v14 37/39] sched/deadline: Warn when a runqueue keeps the bandwidth of a task

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: Cold p->dl load in set_task_cpu() on non-DL migrations - [Low] sched/deadline…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: Cold p->dl load in set_task_cpu() on non-DL migrations
- [Low] sched/deadline: Changelog cites __dl_clear_params() not dl_release_params()
--

commit c63aaa2809cc1d85748f1c6385d4f67c969d9e4e
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Warn when a runqueue keeps the bandwidth of a task

This commit adds WARN_ON_ONCE() checks in set_task_cpu(), task_non_contending(), and inactive_task_timer() to catch cases where dl_bw_oncpu remains set after a task leaves the deadline class or before its deadline parameters are released.

Quoted 4 lines

- task_non_contending() or inactive_task_timer() releases the bandwidth of a task while its flag is still set. They then call __dl_clear_params(), which clears both the flag and dl_bw. After that, nothing can take the bandwidth off the runqueue.

[ ... ]

Quoted 3 lines

Warn about the first state in set_task_cpu(). Warn about the second in task_non_contending() and inactive_task_timer(), before they call __dl_clear_params(). No warning fires in the selftests of this series.

[Severity: Low]
Both task_non_contending() and inactive_task_timer() actually call dl_release_params(), which invokes __dl_clear_params() internally and preserves period_start and deadline for constrained-deadline tasks. Should the changelog refer to dl_release_params() instead?

[ ... ]

kernel/sched/core.c void set_task_cpu(struct task_struct *p, unsigned int new_cpu) · line 3521

Quoted 10 lines
kernel/sched/core.c +2 -0
index 2700c8e98b0ed..879ac7d6cdfd0 100644
@@ -3517,6 +3517,9 @@ void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
 	 */
 	WARN_ON_ONCE(!cpu_online(new_cpu));
 
+	/* A task of another class would leave its bandwidth in this_bw. */
+	WARN_ON_ONCE(!dl_task(p) && p->dl.dl_bw_oncpu);

[Severity: Medium]
Does this unconditionally load a cold cacheline in p->dl on every non-deadline task migration?

set_task_cpu() runs on hot paths such as try_to_wake_up() and detach_task(), under p->pi_lock or rq->__lock with IRQs disabled. Non-deadline paths do not otherwise touch p->dl, so reading dl_bw_oncpu adds a cold cacheline load on every migration even without deadline tasks.

Checking here also only fires belatedly on an unrelated migration trace, misses tasks that stay on one CPU, and is compiled out without CONFIG_SMP.

Checking WARN_ON_ONCE(p->dl.dl_bw_oncpu) in switched_from_dl(), where p->dl is already hot in cache, or gating this check behind CONFIG_SCHED_DEBUG would avoid penalizing non-deadline migrations while catching class-exit leaks at the source.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=37
#58 lore raw

PATCH v14 38/39 selftests/sched: Test PI against hotplug and rebuilds in deadline_bw_test

In reply to Mathieu Desnoyers

Add two cases to deadline_bw_test. The comment above each case gives its scenario. Each case fails without one fix of this series:
- pi_departed_offline_boost. A task leaves SCHED_DEADLINE while its root domain still counts its bandwidth. Then the CPU recorded with that bandwidth goes offline. The rebuild of the accounting that follows drops the bandwidth. A deadline waiter then boosts the task back into the class. The case checks that total_bw counts the task again. The fix is "sched/deadline: Count again a departed task that a boost brings back". Without it, the case failed in every run.
- pi_deboost_during_rebuild. The timeout of a deadline waiter deboosts a task while a rebuild of the accounting walks the task list. The case checks that total_bw still counts the task right after the rebuild. The fix is "sched/deadline: Count a task that departs while a rebuild walks the tasks".

pi_deboost_during_rebuild tests a race. It runs rounds for 25s, and fails at the first round where total_bw misses the task. A filler process of 1000 threads is forked before the task. The walk meets these threads first, so the race window is wider. Without the fix, 35 of 43 runs failed.

pi_departed_offline_boost needs 4 housekeeping CPUs, two of them hotpluggable. pi_deboost_during_rebuild needs 5. Each case skips without them.

With the whole series, both cases pass in every run. No kernel warning is logged.

---
 .../sched/deadline/deadline_bw_test.c         | 489 +++++++++++++++++-
 1 file changed, 483 insertions(+), 6 deletions(-)
tools/testing/selftests/sched/deadline/deadline_bw_test.c +483 -6
index 58ec444cf1bb..90f2f19bfb72 100644
@@ -40,15 +40,16 @@
  * hotplug cases, and the cases with no_hp set, which take no CPU
  * offline. The test skips the hotplug cases if no CPU can go offline. It
  * still runs the no_hp ones.
- * death_zombie_hotplug takes CPUs offline too, but it is in p_cases[]: it
- * needs the cpuset setup of those cases.
+ * death_zombie_hotplug and pi_departed_offline_boost take CPUs offline
+ * too, but they are in p_cases[]: they need the cpuset setup of those
+ * cases.
  *
  * The server cases change the fair server of a CPU through debugfs, and
  * the test then puts it back.
  *
  * The test needs root, deadline admission control and 3 housekeeping
- * CPUs. Some cases need 4. Most also need the cgroup v2 cpuset
- * controller. Some need debugfs or CPU hotplug. Twenty-nine need
+ * CPUs. Some cases need 4, one needs 5. Most also need the cgroup v2
+ * cpuset controller. Some need debugfs or CPU hotplug. Twenty-nine need
  * isolcpus="domain" at boot.
  */
 #define _GNU_SOURCE
@@ -8246,8 +8247,9 @@ static int random_mix(void)
 }
 
 /*
- * CPU hotplug, from the main process, with no P. Two cases below run with
- * P instead: death_zombie_hotplug and pi_departed_moved.
+ * CPU hotplug, from the main process, with no P. Three cases below run
+ * with P instead: death_zombie_hotplug, pi_departed_moved and
+ * pi_departed_offline_boost.
  */
 
 static int hp_cpu = -1;
@@ -8836,6 +8838,163 @@ static int pi_departed_moved(void)
 	return ret;
 }
 
+/*
+ * Q is a partition root of CPUs X and Y. The owner is a deadline task of
+ * 200ms every 2s in Q. The steps:
+ * 1. The owner takes shm_lock, runs 180ms and sleeps on X. Its 0-lag
+ *    time is about 1.6s ahead.
+ * 2. The case switches the owner to SCHED_OTHER. The root domain of Q
+ *    keeps its bandwidth until the 0-lag time. The kernel records X with
+ *    that bandwidth.
+ * 3. The case pins the owner to Y and wakes it up. It runs on Y, then
+ *    sleeps there. The record stays X.
+ * 4. The case takes X offline, which rebuilds the accounting. The
+ *    recorded CPU is no longer active, so the rebuild drops the
+ *    bandwidth of the owner.
+ * 5. A deadline waiter of 5ms every 50ms, outside Q, blocks on shm_lock.
+ *    It boosts the owner back into the class.
+ *
+ * The boost must add the bandwidth of the owner to this_bw of Y, and to
+ * total_bw of Q. Once the owner and the waiter are gone, past the 0-lag
+ * time, total_bw of Q must be what it was at the start.
+ */
+static int pi_departed_offline_boost(void)
+{
+	int cpu[2] = { top_cpu(3), top_cpu(2) }, x, y, ret = KSFT_FAIL;
+	long long base, bw, off, boosted;
+	long this0, this1, running;
+	pid_t owner = -1, waiter = -1;
+	char cpus[32];
+	cpu_set_t set;
+	uint64_t t;
+
+	if (ncpus < 4 || !cpu_hotpluggable(cpu[0]) || !cpu_hotpluggable(cpu[1])) {
+		ksft_print_msg("needs 4 non-isolated CPUs, 2 hotpluggable beside P\n");
+		return KSFT_SKIP;
+	}
+	snprintf(cpus, sizeof(cpus), "%d,%d", cpu[0], cpu[1]);
+	if (make_partition_cpus(cg_q, cpus)) {
+		ksft_print_msg("no partition root Q of CPUs %s\n", cpus);
+		remove_partition(cg_q);
+		return KSFT_SKIP;
+	}
+	base = total_bw_of(cpu[0]);
+	if (base < 0 || rq_bw_of(cpu[0], &this0, &running)) {
+		ksft_print_msg("no total_bw or this_bw in /sys/kernel/debug/sched/debug\n");
+		remove_partition(cg_q);
+		return KSFT_SKIP;
+	}
+	if (shm_lock_init()) {
+		remove_partition(cg_q);
+		return KSFT_SKIP;
+	}
+	bw = (ZOMBIE_RUNTIME << 20) / ZOMBIE_PERIOD;	/* as to_ratio() */
+	mv_state[1] = 0;
+	mv_state[3] = 0;
+	owner = fork_child("the owner of the lock");
+	if (!owner) {
+		signal(SIGUSR1, no_op);
+		if (enter(cg_q, getpid()) || pthread_mutex_lock(shm_lock) ||
+		    set_deadline(0, ZOMBIE_RUNTIME, ZOMBIE_PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		/* 20ms left: the 0-lag time is 200ms before the deadline. */
+		spin_ns(ZOMBIE_RUNTIME - 20 * NSEC_PER_MSEC);
+		mv_state[0] = 1;
+		while (!mv_state[3])
+			pause();
+		mv_state[1] = 1;
+		for (;;)
+			pause();
+	}
+	if (owner < 0 || child_up("the owner of the lock", 0))
+		goto out;
+	t = now_ns();
+	if (wait_for(100, proc_state_of(owner) == 'S')) {
+		ksft_print_msg("the owner is not asleep\n");
+		goto out;
+	}
+	/* Step 2. Asleep, the owner departs from the CPU it sleeps on. */
+	if (set_other(owner)) {
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+		goto out;
+	}
+	x = task_cpu_of(owner);
+	if (x != cpu[0] && x != cpu[1]) {
+		ksft_print_msg("the owner sleeps on CPU %d, not in Q\n", x);
+		goto out;
+	}
+	y = x == cpu[0] ? cpu[1] : cpu[0];
+	/* Step 3 */
+	CPU_ZERO(&set);
+	CPU_SET(y, &set);
+	if (sched_setaffinity(owner, sizeof(set), &set)) {
+		ksft_print_msg("the owner cannot be pinned to CPU %d: %s\n", y, strerror(errno));
+		goto out;
+	}
+	mv_state[3] = 1;
+	kill(owner, SIGUSR1);
+	if (wait_state(&mv_state[1], 1) || wait_for(500, proc_state_of(owner) == 'S') ||
+	    task_cpu_of(owner) != y) {
+		ksft_print_msg("the owner did not move to CPU %d\n", y);
+		goto out;
+	}
+	/* Step 4 */
+	if (cpu_online(x, 0)) {
+		ksft_print_msg("CPU %d cannot go offline\n", x);
+		goto out;
+	}
+	off = total_bw_of(y);
+	if (rq_bw_of(y, &this0, &running)) {
+		ksft_print_msg("no this_bw of CPU %d\n", y);
+		goto online;
+	}
+	/* Step 5 */
+	waiter = lock_waiter();
+	if (waiter < 0 || wait_state(&mv_state[2], 1)) {
+		ksft_print_msg("no waiter\n");
+		goto online;
+	}
+	sleep_ns(50 * NSEC_PER_MSEC);	/* blocked, boosting the owner */
+	if (prio_of(owner) != DL_TASK_PRIO) {
+		ksft_print_msg("the owner is not boosted: prio %d\n", prio_of(owner));
+		goto online;
+	}
+	boosted = total_bw_of(y);
+	if (rq_bw_of(y, &this1, &running)) {
+		ksft_print_msg("no this_bw of CPU %d\n", y);
+	} else if (now_ns() - t > NSEC_PER_SEC) {
+		ksft_print_msg("the steps took over 1s: the 0-lag time may be past\n");
+		ret = KSFT_SKIP;
+	} else if (this1 - this0 != bw) {
+		ksft_print_msg("the boost adds %ld to this_bw of CPU %d, %lld expected\n",
+			       this1 - this0, y, bw);
+	} else if (boosted != off + bw) {
+		ksft_print_msg("total_bw of Q: %lld boosted, %lld expected%s\n",
+			       boosted, off + bw,
+			       boosted == off ? ": the owner is not counted" : "");
+	} else {
+		ret = KSFT_PASS;
+	}
+online:
+	reap(waiter);
+	cpu_up(x);
+out:
+	reap(owner);
+	if (ret == KSFT_PASS) {
+		sleep_ns(ZOMBIE_PERIOD);	/* past the 0-lag time of the owner */
+		off = total_bw_of(cpu[0]);
+		if (off != base) {
+			ksft_print_msg("total_bw of Q past the 0-lag time: %lld, %lld expected\n",
+				       off, base);
+			ret = KSFT_FAIL;
+		}
+	}
+	remove_partition(cg_q);
+	return ret;
+}
+
 /*
  * The bandwidth of a fair server must leave the root domain with its CPU
  * and come back with it, whatever its size. Probe the housekeeping root
@@ -12504,6 +12663,322 @@ static int affinity_vs_setattr(void)
 	return ret;
 }
 
+/* A deboost against a rebuild of the accounting */
+
+#define RACE_T_RUNTIME	(20 * NSEC_PER_MSEC)
+#define RACE_T_PERIOD	(200 * NSEC_PER_MSEC)
+#define RACE_W_RUNTIME	(5 * NSEC_PER_MSEC)
+#define RACE_W_PERIOD	(50 * NSEC_PER_MSEC)
+#define RACE_FILLERS	1000
+#define RACE_SECS	25
+
+/*
+ * The state that pi_deboost_during_rebuild() shares with its processes,
+ * in shared memory. T and W are the threads that its comment describes.
+ * go and w_go count the rounds of T and W. t_ready and w_done tell the
+ * case that a round of T or of W is done.
+ */
+static struct race_shm {
+	atomic_int go, t_ready, w_go, w_blocked, w_done, w_err, fill;
+	_Atomic pid_t t_tid, w_tid;
+	_Atomic int64_t w_abs, w_ret;
+} *rs;
+
+/* The priority inheritance mutex of T and W, threads of one process */
+static pthread_mutex_t race_m;
+
+static int64_t realtime_ns(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_REALTIME, &ts);
+	return (int64_t)ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
+}
+
+/* Wait for the futex @f, in shared memory, to change from @val. */
+static void wait_change(atomic_int *f, int val)
+{
+	while (*f == val)
+		syscall(SYS_futex, f, FUTEX_WAIT, val, NULL, NULL, 0);
+}
+
+static void *race_filler(void *arg)
+{
+	for (;;)
+		pause();
+	return arg;
+}
+
+/*
+ * W: become a deadline task. In each round, block on race_m until the
+ * time rs->w_abs, CLOCK_REALTIME. The wait must time out: T holds
+ * race_m.
+ */
+static void *race_w(void *arg)
+{
+	int i = 0;
+
+	rs->w_tid = gettid_();
+	if (set_deadline(0, RACE_W_RUNTIME, RACE_W_PERIOD)) {
+		set_flag(&rs->w_err, -1);
+		return arg;
+	}
+	for (;;) {
+		struct timespec ts;
+		int err;
+
+		wait_change(&rs->w_go, i);
+		i = rs->w_go;
+		if (i < 0)
+			return arg;
+		ts.tv_sec = rs->w_abs / NSEC_PER_SEC;
+		ts.tv_nsec = rs->w_abs % NSEC_PER_SEC;
+		rs->w_blocked = i;
+		err = pthread_mutex_timedlock(&race_m, &ts);
+		rs->w_ret = realtime_ns();
+		if (!err) {
+			pthread_mutex_unlock(&race_m);
+			rs->w_err = 1;
+		} else if (err != ETIMEDOUT) {
+			rs->w_err = 2;
+		}
+		set_flag(&rs->w_done, i);
+	}
+}
+
+/*
+ * Fork the process of T and W, in the cgroup @cg. T, its main thread,
+ * takes race_m and starts W. In each round, T makes itself a deadline
+ * task, runs most of its runtime and sleeps. Return the pid, or -1.
+ */
+static pid_t race_t(const char *cg)
+{
+	pid_t pid = fork_child("T and W");
+
+	if (!pid) {
+		pthread_mutexattr_t a;
+		pthread_t w;
+		int i = 0;
+
+		if (enter(cg, getpid()) || pthread_mutexattr_init(&a) ||
+		    pthread_mutexattr_setprotocol(&a, PTHREAD_PRIO_INHERIT) ||
+		    pthread_mutex_init(&race_m, &a) || pthread_mutex_lock(&race_m) ||
+		    pthread_create(&w, NULL, race_w, NULL)) {
+			set_flag(&rs->w_err, -1);
+			_exit(1);
+		}
+		rs->t_tid = gettid_();
+		for (;;) {
+			wait_change(&rs->go, i);
+			i = rs->go;
+			if (i < 0)
+				_exit(0);
+			if (set_deadline(0, RACE_T_RUNTIME, RACE_T_PERIOD)) {
+				set_flag(&rs->t_ready, -i);
+				continue;
+			}
+			/* 2ms left: the 0-lag time is 20ms before the deadline. */
+			spin_ns(RACE_T_RUNTIME - 2 * NSEC_PER_MSEC);
+			set_flag(&rs->t_ready, i);
+		}
+	}
+	return pid;
+}
+
+/*
+ * Fork a process of RACE_FILLERS threads that sleep. Return its pid, or
+ * -1. It sets rs->fill to the count of threads it made, or to -1.
+ */
+static pid_t race_fill(void)
+{
+	pid_t pid = fork_child("the filler");
+
+	if (!pid) {
+		pthread_attr_t at;
+		pthread_t t;
+		int n;
+
+		pthread_attr_init(&at);
+		pthread_attr_setstacksize(&at, THREAD_STACK);
+		for (n = 0; n < RACE_FILLERS; n++) {
+			if (pthread_create(&t, &at, race_filler, NULL))
+				break;
+		}
+		set_flag(&rs->fill, n ? n : -1);
+		for (;;)
+			pause();
+	}
+	return pid;
+}
+
+/* Toggle Q between a partition root and a member. Return 0, or -errno. */
+static int toggle_q(int *q_root)
+{
+	*q_root = !*q_root;
+	return write_file(cg_q, "cpuset.cpus.partition", *q_root ? "root" : "member");
+}
+
+/*
+ * A rebuild of the accounting clears the bandwidth of the root domains,
+ * then walks the task list and adds back each deadline task. A task can
+ * leave the class in the window between the clear and the walk reaching
+ * it. It must still be counted until its 0-lag time.
+ *
+ * R is a partition root of two CPUs. Q is a partition root of one CPU. T
+ * and W are threads of one process in R. T holds race_m, a priority
+ * inheritance mutex. Before T and W, the case forks a filler process of
+ * RACE_FILLERS threads that sleep. The walk meets them before T, which
+ * makes the window wider. In each round:
+ * 1. T makes itself a deadline task of 20ms every 200ms. It runs 18ms
+ *    and sleeps. Its 0-lag time is about 160ms ahead.
+ * 2. W, a deadline task of 5ms every 50ms, blocks on race_m with a
+ *    timeout. It boosts T.
+ * 3. The case switches T to SCHED_OTHER. The boost keeps T in the class.
+ * 4. The case switches Q between member and partition root. This
+ *    rebuilds the accounting. The case times the write so that the
+ *    timeout of W falls in it, at a random point. The timeout ends the
+ *    boost: T leaves the class before its 0-lag time.
+ * 5. Right after, total_bw of R must count W and T.
+ * 6. Past the 0-lag time of T, total_bw of R must count W only.
+ *
+ * The rounds run for RACE_SECS seconds. The case fails at the first
+ * round where total_bw of R misses T.
+ */
+static int pi_deboost_during_rebuild(void)
+{
+	int cpu[2], q_root = 1, ret = KSFT_FAIL, i;
+	long long base, bw_t, bw_w, tb;
+	char cg_r[PATH_MAX + 32], cpus[32];
+	pid_t filler = -1, proc = -1;
+	uint64_t end, d, dmax = 0;
+
+	if (ncpus < 5) {
+		ksft_print_msg("needs 5 non-isolated CPUs\n");
+		return KSFT_SKIP;
+	}
+	cpu[0] = top_cpu(4);
+	cpu[1] = top_cpu(3);
+	snprintf(cg_r, sizeof(cg_r), "%s/deadline_bw_r", root);
+	snprintf(cpus, sizeof(cpus), "%d,%d", cpu[0], cpu[1]);
+	if (make_partition_cpus(cg_r, cpus) || make_partition(cg_q, top_cpu(2))) {
+		ksft_print_msg("no partition roots R of CPUs %s and Q of CPU %d\n",
+			       cpus, top_cpu(2));
+		ret = KSFT_SKIP;
+		goto out_cg;
+	}
+	rs = mmap(NULL, sizeof(*rs), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
+	if (rs == MAP_FAILED) {
+		ksft_print_msg("mmap: %s\n", strerror(errno));
+		goto out_cg;
+	}
+	memset(rs, 0, sizeof(*rs));
+	bw_t = bw_of(RACE_T_RUNTIME, RACE_T_PERIOD);
+	bw_w = bw_of(RACE_W_RUNTIME, RACE_W_PERIOD);
+
+	filler = race_fill();
+	if (filler < 0 || wait_for(10000, rs->fill) || rs->fill < 0) {
+		ksft_print_msg("no filler threads\n");
+		goto out;
+	}
+	/* The longest of 8 writes to Q sets the range of the timeouts. */
+	for (i = 0; i < 8; i++) {
+		uint64_t t = now_ns();
+
+		if (toggle_q(&q_root)) {
+			ksft_print_msg("Q cannot change between root and member\n");
+			ret = KSFT_SKIP;
+			goto out;
+		}
+		d = now_ns() - t;
+		if (d > dmax)
+			dmax = d;
+	}
+	if (total_bw_of(cpu[0]) < 0) {
+		ksft_print_msg("no total_bw in /sys/kernel/debug/sched/debug\n");
+		ret = KSFT_SKIP;
+		goto out;
+	}
+	proc = race_t(cg_r);
+	if (proc < 0 || wait_for(2000, (rs->w_tid && rs->t_tid) || rs->w_err) || rs->w_err) {
+		ksft_print_msg("no T and W\n");
+		goto out;
+	}
+	sleep_ns(100 * NSEC_PER_MSEC);
+	base = total_bw_of(cpu[0]) - bw_w;
+
+	srand(getpid() ^ now_ns());
+	end = now_ns() + RACE_SECS * NSEC_PER_SEC;
+	for (i = 1; now_ns() < end; i++) {
+		int64_t abs, lead, w0;
+		struct timespec ts;
+
+		set_flag(&rs->go, i);
+		if (wait_for_step(1000, 100 * NSEC_PER_USEC,
+				  rs->t_ready == i || rs->t_ready == -i) ||
+		    rs->t_ready != i) {
+			ksft_print_msg("round %d: T cannot become a deadline task\n", i);
+			goto out;
+		}
+		if (wait_for_step(100, 100 * NSEC_PER_USEC, proc_state_of(rs->t_tid) == 'S'))
+			continue;
+		/* Leave W 20ms to block, then time out within the write. */
+		lead = (int64_t)((double)rand() / RAND_MAX * 1.2 * dmax);
+		abs = realtime_ns() + 20 * NSEC_PER_MSEC + dmax;
+		rs->w_abs = abs;
+		set_flag(&rs->w_go, i);
+		if (wait_for_step(100, 100 * NSEC_PER_USEC, rs->w_blocked == i) ||
+		    wait_for_step(100, 100 * NSEC_PER_USEC, proc_state_of(rs->w_tid) == 'S')) {
+			ksft_print_msg("round %d: W did not block\n", i);
+			goto out;
+		}
+		if (set_other(rs->t_tid)) {
+			ksft_print_msg("round %d: T cannot leave SCHED_DEADLINE\n", i);
+			goto out;
+		}
+		if (prio_of(rs->t_tid) != DL_TASK_PRIO) {
+			ksft_print_msg("round %d: W does not boost T\n", i);
+			goto out;
+		}
+		ts.tv_sec = (abs - lead) / NSEC_PER_SEC;
+		ts.tv_nsec = (abs - lead) % NSEC_PER_SEC;
+		while (clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &ts, NULL) == EINTR)
+			;
+		w0 = realtime_ns();
+		toggle_q(&q_root);
+		d = realtime_ns() - w0;
+		if (wait_for_step(1000, 100 * NSEC_PER_USEC, rs->w_done == i) || rs->w_err) {
+			ksft_print_msg("round %d: the wait of W did not time out\n", i);
+			goto out;
+		}
+		tb = total_bw_of(cpu[0]);
+		if (tb != base + bw_w + bw_t) {
+			ksft_print_msg("round %d: total_bw of R %lld, %lld expected%s\n",
+				       i, tb, base + bw_w + bw_t,
+				       tb == base + bw_w ? ": T is missing" : "");
+			ksft_print_msg("round %d: timeout %lldus into a write of %lldus\n",
+				       i, (long long)(rs->w_ret - w0) / 1000, (long long)d / 1000);
+			goto out;
+		}
+		/* Past the 0-lag time of T: R counts W only. */
+		if (wait_for_step(1000, 5 * NSEC_PER_MSEC, total_bw_of(cpu[0]) == base + bw_w)) {
+			ksft_print_msg("round %d: past the 0-lag time of T, total_bw of R %lld, %lld expected\n",
+				       i, total_bw_of(cpu[0]), base + bw_w);
+			goto out;
+		}
+	}
+	ret = KSFT_PASS;
+out:
+	set_flag(&rs->go, -1);
+	set_flag(&rs->w_go, -1);
+	reap(proc);
+	reap(filler);
+	munmap(rs, sizeof(*rs));
+out_cg:
+	remove_partition(cg_q);
+	remove_partition(cg_r);
+	return ret;
+}
+
 /* The tables of the cases, and main() */
 
 enum where {
@@ -12522,6 +12997,7 @@ static const struct p_case {
 	{ "pi_unlock_running", pi_unlock_running, MEASURED_IN_P },
 	{ "pi_chain_two_owners", pi_chain_two_owners, MEASURED_IN_P },
 	{ "pi_departed_moved", pi_departed_moved, FROM_OUTSIDE },
+	{ "pi_departed_offline_boost", pi_departed_offline_boost, FROM_OUTSIDE },
 	{ "params_asleep", params_asleep, IN_P },
 	{ "params_non_contending", params_non_contending, MEASURED_IN_P },
 	{ "params_switched_asleep", params_switched_asleep, MEASURED_IN_P },
@@ -12612,6 +13088,7 @@ static const struct p_case {
 	{ "params_swap_overload", params_swap_overload, FROM_OUTSIDE },
 	{ "random_mix", random_mix, FROM_OUTSIDE },
 	{ "move_normalized", move_normalized, FROM_OUTSIDE },
+	{ "pi_deboost_during_rebuild", pi_deboost_during_rebuild, FROM_OUTSIDE },
 };
 
 #define N_P_CASES	((int)ARRAY_SIZE(p_cases))
Signature · 1 line
2.47.3
#59 lore raw

Re: [PATCH v14 38/39] selftests/sched: Test PI against hotplug and rebuilds in deadline_bw_test

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Medium] selftests/sched: untracked continue in pi_deboost_during_rebuild() loop - [Low] selftests/sched…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Medium] selftests/sched: untracked continue in pi_deboost_during_rebuild() loop
- [Low] selftests/sched: race_w() publishes rs->w_tid before set_deadline()
- [Low] selftests/sched: unbounded dmax can pass 0-lag time in deadline_bw_test
- [Low] selftests/sched: pi_deboost_during_rebuild() fails instead of skipping
- [Low] selftests/sched: dmax calibrated before deadline tasks in deadline_bw_test
- [Low] selftests/sched: missing w_done check in pi_deboost_during_rebuild()
- [Low] selftests/sched: heavy sched/debug polling in pi_deboost_during_rebuild()
--

commit 422a087312079e778dce123e41c2cb32e6f07e4b
Author: Mathieu Desnoyers <[email protected]>

selftests/sched: Test PI against hotplug and rebuilds in deadline_bw_test

This commit adds two priority-inheritance test cases to deadline_bw_test:
pi_departed_offline_boost and pi_deboost_during_rebuild.

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
index 58ec444cf1bbf..90f2f19bfb72b 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
@@ -12504,6 +12663,322 @@ static int affinity_vs_setattr(void)

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int affinity_vs_setattr(void) · line 12725

Quoted 9 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +9 -0
+static void *race_w(void *arg)
+{
+	int i = 0;
+
+	rs->w_tid = gettid_();
+	if (set_deadline(0, RACE_W_RUNTIME, RACE_W_PERIOD)) {
+		set_flag(&rs->w_err, -1);
+		return arg;
+	}

[Severity: Low]
Can publishing rs->w_tid before set_deadline() race with the parent's startup check in pi_deboost_during_rebuild()?

parent W (race_w)

                                    rs->w_tid = gettid_()
wait_for(..., rs->w_tid && ...)
  sees rs->w_tid != 0, w_err == 0
                                    set_deadline(...) fails
                                      set_flag(&rs->w_err, -1)
                                      return arg

sleep_ns(100ms)
base = total_bw_of(...) - bw_w <-- W was never admitted

Because rs->w_tid is visible before set_deadline() finishes, the parent can pass its startup wait with rs->w_err == 0, compute a corrupted base, and fail later in round 1 instead of catching the startup failure. Even when set_deadline() succeeds, a delay past the 100ms sleep leaves base off by -bw_w. Moving rs->w_tid = gettid_() after the set_deadline() check closes both races.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int affinity_vs_setattr(void) · line 12769

Quoted 7 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +7 -0
+		if (enter(cg, getpid()) || pthread_mutexattr_init(&a) ||
+		    pthread_mutexattr_setprotocol(&a, PTHREAD_PRIO_INHERIT) ||
+		    pthread_mutex_init(&race_m, &a) || pthread_mutex_lock(&race_m) ||
+		    pthread_create(&w, NULL, race_w, NULL)) {
+			set_flag(&rs->w_err, -1);
+			_exit(1);
+		}

[Severity: Low]
Should missing PTHREAD_PRIO_INHERIT support skip the test instead of failing it?

Other PI cases in deadline_bw_test.c (such as pi_init() callers and shm_lock_init()) return KSFT_SKIP when PI mutex setup fails, whereas here rs->w_err = -1 jumps to out: with ret left at KSFT_FAIL. Distinguishing PI mutex initialization failure from other setup errors would keep this case consistent with kselftest policy on kernels without CONFIG_FUTEX_PI or C libraries without PI mutex support.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int affinity_vs_setattr(void) · line 12895

Quoted 13 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +13 -0
+	/* The longest of 8 writes to Q sets the range of the timeouts. */
+	for (i = 0; i < 8; i++) {
+		uint64_t t = now_ns();
+
+		if (toggle_q(&q_root)) {
+			ksft_print_msg("Q cannot change between root and member\n");
+			ret = KSFT_SKIP;
+			goto out;
+		}
+		d = now_ns() - t;
+		if (d > dmax)
+			dmax = d;
+	}

[Severity: Low]
Does calibrating dmax before starting race_t(cg_r) miss the 1000-thread tasklist walk?

When no SCHED_DEADLINE task exists yet, dl_nr_bw_tasks is 0 and dl_rebuild_rd_accounting() returns early before walking for_each_process_thread(). During the actual rounds, W and T are deadline tasks, so the walk runs at the end of partition_sched_domains_locked() and can fall past the 1.2 * dmax lead window, reducing race coverage. Running the 8 calibration writes after race_t(cg_r) starts W would measure the full rebuild duration.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int affinity_vs_setattr(void) · line 12923

Quoted 2 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +2 -0
+		if (wait_for_step(100, 100 * NSEC_PER_USEC, proc_state_of(rs->t_tid) == 'S'))
+			continue;

[Severity: Medium]
Can this continue allow pi_deboost_during_rebuild() to report KSFT_PASS after executing zero rounds?

If runtime overhead exceeds the 2ms margin left after spin_ns(), T gets throttled in state 'R' for ~180ms, exceeding the 100ms wait on every iteration until the 25-second loop ends and unconditionally sets ret = KSFT_PASS. Tracking completed rounds and failing or skipping when none complete would prevent a silent pass.

Also, jumping to continue skips set_other(rs->t_tid), so T stays in SCHED_DEADLINE with identical parameters and the next round's set_deadline() hits the no-op path in __sched_setscheduler() instead of starting a fresh period.

Quoted 8 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +8 -0
+		/* Leave W 20ms to block, then time out within the write. */
+		lead = (int64_t)((double)rand() / RAND_MAX * 1.2 * dmax);
+		abs = realtime_ns() + 20 * NSEC_PER_MSEC + dmax;
+		rs->w_abs = abs;
+		set_flag(&rs->w_go, i);
+		if (wait_for_step(100, 100 * NSEC_PER_USEC, rs->w_blocked == i) ||
+		    wait_for_step(100, 100 * NSEC_PER_USEC, proc_state_of(rs->w_tid) == 'S')) {
+			ksft_print_msg("round %d: W did not block\n", i);

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int affinity_vs_setattr(void) · line 12941

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +10 -0
+			goto out;
+		}
+		if (set_other(rs->t_tid)) {
+			ksft_print_msg("round %d: T cannot leave SCHED_DEADLINE\n", i);
+			goto out;
+		}
+		if (prio_of(rs->t_tid) != DL_TASK_PRIO) {
+			ksft_print_msg("round %d: W does not boost T\n", i);
+			goto out;
+		}

[Severity: Low]
Can an early timeout of W trigger a spurious "W does not boost T" failure?

parent W (race_w)
abs = realtime_ns() + 20ms + dmax
set_flag(&rs->w_go, i)

                                    rs->w_blocked = i
                                    pthread_mutex_timedlock(&race_m, &ts)
(delayed > 20ms + dmax)               times out, deboosts T
                                    set_flag(&rs->w_done, i)
                                    wait_change(&rs->w_go, i)  (state 'S')

proc_state_of(rs->w_tid) == 'S' set_other(rs->t_tid)
prio_of(rs->t_tid) != DL_TASK_PRIO <-- spurious KSFT_FAIL

Because wait_change() also sleeps in state 'S', the parent cannot tell whether W is still blocked on race_m or has already timed out and deboosted T. Checking rs->w_done == i before treating the prio check as a kernel PI failure would distinguish an early timeout from a boost bug.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int affinity_vs_setattr(void) · line 12957

Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +5 -0
+		tb = total_bw_of(cpu[0]);
+		if (tb != base + bw_w + bw_t) {
+			ksft_print_msg("round %d: total_bw of R %lld, %lld expected%s\n",
+				       i, tb, base + bw_w + bw_t,
+				       tb == base + bw_w ? ": T is missing" : "");

[Severity: Low]
Can an uncapped dmax push this total_bw_of(cpu[0]) read past T's 0-lag time and cause a false failure?

T's 0-lag time is at most ~162ms after it sleeps, while when lead is near 0, toggle_q() finishes roughly 20ms + 2 * dmax after T slept. On slower, virtualized, or debug kernels where dmax is ~70ms or more (or a single rebuild stalls), T's inactive timer can legitimately release bw_t before this read runs. Bounding dmax or checking elapsed time since T slept, as pi_departed_offline_boost() does, would avoid false KSFT_FAIL results.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int affinity_vs_setattr(void) · line 12963

Quoted 2 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +2 -0
+		/* Past the 0-lag time of T: R counts W only. */
+		if (wait_for_step(1000, 5 * NSEC_PER_MSEC, total_bw_of(cpu[0]) == base + bw_w)) {

[Severity: Low]
Will polling total_bw_of(cpu[0]) every 5ms scale poorly on large SMP systems?

Partition R is placed on top_cpu(4) and top_cpu(3), so each call to total_bw_of(cpu[0]) streams /sys/kernel/debug/sched/debug across nearly every online CPU, and print_rq() walks all threads (including the 1000 filler threads) under rcu_read_lock() for each CPU printed. Polling every 5ms across T's ~100-130ms 0-lag wait cuts into round throughput and makes the earlier total_bw_of(cpu[0]) read more likely to overrun the 0-lag window; placing R on low-numbered CPUs or sleeping toward the 0-lag time before polling would reduce that overhead.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=38
#60 lore raw

PATCH v14 39/39 selftests/sched: Share the helpers of the deadline tests

In reply to Mathieu Desnoyers

deadline_bw_test, deadline_rebuild_test and deadline_switch_test each have a copy of the same helpers. Move these to deadline_util.h:
- now_ns(), thread_time_ns() and sleep_ns();
- report();
- read_file(), write_file() and enter().

deadline_rebuild_test uses thread_time_ns() in place of its own cpu_time_ns(). The helpers that differ from one test to the other stay in each test. The Makefile adds the header to LOCAL_HDRS, so that lib.mk rebuilds the tests when the header changes.

The Sashiko AI review of this series asked for this. No case changes.

---
 .../testing/selftests/sched/deadline/Makefile |   2 +
 .../sched/deadline/deadline_bw_test.c         |  86 +-------------
 .../sched/deadline/deadline_rebuild_test.c    |  94 +---------------
 .../sched/deadline/deadline_switch_test.c     |  36 +-----
 .../selftests/sched/deadline/deadline_util.h  | 106 ++++++++++++++++++
 5 files changed, 116 insertions(+), 208 deletions(-)
 create mode 100644 tools/testing/selftests/sched/deadline/deadline_util.h
tools/testing/selftests/sched/deadline/Makefile +2 -0
index 15f1e96a21e6..a81aa97c6cc6 100644
@@ -5,4 +5,6 @@ LDLIBS += -lpthread
 
 TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test deadline_bw_test
 
+LOCAL_HDRS += deadline_util.h
+
 include ../../lib.mk
tools/testing/selftests/sched/deadline/deadline_bw_test.c +2 -84

110 lines not on this page · raw message

tools/testing/selftests/sched/deadline/deadline_rebuild_test.c +4 -90

130 lines not on this page · raw message

tools/testing/selftests/sched/deadline/deadline_switch_test.c +2 -34
index 40c7c6bafc2b..a544bee5af5a 100644
@@ -51,6 +51,8 @@
 #define NSEC_PER_MSEC	1000000ULL
 #define NSEC_PER_SEC	1000000000ULL
 
+#include "deadline_util.h"
+
 struct dl_attr {
 	uint32_t size;
 	uint32_t sched_policy;
@@ -70,22 +72,6 @@ struct shared {
 	uint64_t sleeps;	/* sleeps begun */
 };
 
-static uint64_t now_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_MONOTONIC, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
-static void sleep_ns(uint64_t ns)
-{
-	struct timespec ts = { .tv_sec = ns / NSEC_PER_SEC, .tv_nsec = ns % NSEC_PER_SEC };
-
-	while (nanosleep(&ts, &ts) && errno == EINTR)
-		;
-}
-
 static void sleep_until(uint64_t t)
 {
 	struct timespec ts = { .tv_sec = t / NSEC_PER_SEC, .tv_nsec = t % NSEC_PER_SEC };
@@ -518,14 +504,6 @@ static sem_t owner_locked, owner_go;
 static pid_t owner_tid;
 static int owner_ms;		/* the owner's CPU time in its first period */
 
-static uint64_t thread_time_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
 /*
  * Wait on @s for at most @ms, retrying on signals. Return 0, or -1 on a
  * timeout or an error.
@@ -1081,16 +1059,6 @@ static int test_sysrq_running_owner(int normalized)
 	return ret;
 }
 
-static void report(const char *name, int ret)
-{
-	if (ret == KSFT_PASS)
-		ksft_test_result_pass("%s\n", name);
-	else if (ret == KSFT_SKIP)
-		ksft_test_result_skip("%s\n", name);
-	else
-		ksft_test_result_fail("%s\n", name);
-}
-
 int main(void)
 {
 	int ret;
tools/testing/selftests/sched/deadline/deadline_util.h new file +106 -0

106 lines not on this page · raw message

Signature · 1 line
2.47.3