Skip to contentSkip to conversation

sched/deadline: bandwidth accounting fixes and selftests

PATCH New Mathieu Desnoyers 2 participants 59 messages Nov 26 Page 2 of 2

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

PATCH v11 42/43 selftests/sched: Test parameter changes in deadline_bw_test

In reply to Mathieu Desnoyers

Add 39 cases to deadline_bw_test, for the fixes earlier in this series. The comment above each case gives its scenario:
- In 24 cases, a task with runtime left changes its parameters, or comes back to the class 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 11 cases, a lock owner cannot run on its own reservation, so a deadline waiter must boost it. In pi_owner_runs_out_later, pi_owner_wakes_in_gap_later and pi_owner_handed_off, the owner loses its reservation after the waiter blocked. In pi_owner_reboost_loop and pi_owners_reboost_loop, a waiter boosts a throttled owner over and over. Another deadline task must still get its runtime.
- In 4 cases, a constrained task leaves the class in its gap and comes back. The gap is the time between its deadline and its next period.

These cases fail on v7.4-rc2, in each of two VMs of 8 CPUs. In the series, each one fails at the patch before the fix named, 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, change_boosted_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, deboost_out_new_params and params_swap_overload.
- "sched/deadline: Boost an owner that cannot run on its own reservation": pi_owner_asleep_in_gap, pi_owner_throttled, pi_owner_throttled_asleep and pi_owner_held_new_params.
- "sched/deadline: Boost an owner throttled after its waiter blocked":
pi_owner_runs_out_later, pi_owner_wakes_in_gap_later and pi_owner_handed_off.

These cases pass on v7.4-rc2 and with the whole series. A wrong version of the fix named would fail them:
- "sched/deadline: Keep the debt of a task across a change of parameters": deboost_asleep_new_params, 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.
- "sched/deadline: Boost an owner that cannot run on its own reservation": pi_owner_throttled_rival, pi_owner_held_long, pi_owner_reboost_loop and pi_owners_reboost_loop. In the series before that fix, pi_owner_throttled_rival failed in some runs. The last two failed on an earlier version of the fix, in which each boost started a new period of the waiter.

deboost_new_params_reboost passes on v7.4-rc2, and at each patch of this series. On v7.4-rc2, a task made SCHED_DEADLINE while it waits on a PI mutex keeps a deadline of 0. So it boosts the owner in any case. From "sched/deadline: Start a period for a task that enters the class blocked" on, that task gets a real deadline. The case then checks the deboost of "sched/deadline: Keep the debt of a task across a change of parameters". The debt moves the owner's deadline after the waiter's. The deboost must then boost the owner again.

The four reenter_*_in_gap cases pass on v7.4-rc2. On the first series, they fail from these patches on:
- "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.
Three of them pass from "sched/deadline: Count the 0-lag time from the next period" on. reenter_asleep_late_in_gap passes from "sched/deadline: Keep a departing constrained task until its next period" on.

The cases run in P, a one-CPU partition root. 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. 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. Without the wait, random_mix failed in most runs: the this_bw it read dropped when that debt was repaid.

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

---
 .../sched/deadline/deadline_bw_test.c         | 3645 ++++++++++++++++-
 1 file changed, 3608 insertions(+), 37 deletions(-)
tools/testing/selftests/sched/deadline/deadline_bw_test.c +3608 -37
index 83dd8b4e79a3..78b58888e9d5 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 ten other cases: mask_out_refused,
@@ -58,6 +60,7 @@
 #include <fcntl.h>
 #include <limits.h>
 #include <pthread.h>
+#include <sys/klog.h>
 #include <sched.h>
 #include <semaphore.h>
 #include <signal.h>
@@ -284,6 +287,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 };
@@ -2602,6 +2619,163 @@ static int deboost_in_asleep_after_refill(void)
 	return ret;
 }
 
+static sem_t nps_wake;
+static _Atomic pid_t nps_o_tid;
+static _Atomic uint64_t nps_t0;
+
+/*
+ * Run as the owner O of deboost_out_new_params(). Its comment has the
+ * steps. Return NULL, or 1 on an error.
+ */
+static void *nps_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	nps_o_tid = gettid_();
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD);
+	nps_t0 = now_ns();
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&inas_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&inas_locked);
+	t0 = now_ns();
+	while (!inas_locking || proc_state_of(inas_d_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not block on the lock\n");
+			drop_pi_lock();
+			set_other(0);
+			return (void *)1;
+		}
+	}
+	spin_ns(4 * NSEC_PER_MSEC);
+	sem_wait_sig(&nps_wake);
+	drop_pi_lock();
+	set_other(0);
+	return NULL;
+}
+
+/*
+ * A boosted task changes its parameters before any refill, then leaves
+ * the class at its deboost. O and D share the CPU of P:
+ * 1. D becomes a deadline task of 2ms every 50ms, and waits.
+ * 2. O becomes a deadline task of 5ms every 100ms, at 0ms. It takes
+ *    pi_lock.
+ * 3. D waits 30ms for pi_lock. Its deadline is the earlier one: it boosts
+ *    O.
+ * 4. O runs 4ms, within its own runtime, and sleeps, boosted. Its 0-lag
+ *    time is at 100 - 1 * 100 / 5 = 80ms.
+ * 5. The main thread changes O to 5ms every 200ms, then switches O to
+ *    SCHED_OTHER. The boost keeps O in the class.
+ * 6. D times out at about 30ms. O leaves the class at its deboost.
+ *
+ * At the deboost, at 30ms, O has used 4ms. Its old bandwidth of 5% gave
+ * it 1.5ms by then. So O has a debt of 2.5ms. The new bandwidth of 2.5%
+ * repays that at 130ms. O's bandwidth must stay in total_bw until then.
+ * Mixing the runtime and the deadline of the old parameters with the new
+ * ones would put its 0-lag time at 200 - 1 * 200 / 5 = 160ms. The case
+ * reads total_bw at 115ms and at 145ms.
+ */
+static int deboost_out_new_params(void)
+{
+	long long base, with_o = -1, early = -1, late = -1;
+	void *o_ret = NULL, *d_ret = NULL;
+	int err, out = 0, ret = KSFT_FAIL;
+	pthread_t o, d;
+
+	if (total_bw_of(top_cpu(1)) < 0) {
+		ksft_print_msg("sched_debug tells of no total_bw\n");
+		return KSFT_SKIP;
+	}
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&inas_ready, 0, 0) || sem_init(&inas_locked, 0, 0) ||
+	    sem_init(&inas_out, 0, 0) || sem_init(&inas_read, 0, 0) ||
+	    sem_init(&nps_wake, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	inas_locking = 0;
+	inas_d_tid = 0;
+	nps_o_tid = 0;
+	if (pthread_create(&d, NULL, inas_donor, NULL)) {
+		ksft_print_msg("the donor thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&inas_ready, 5000)) {
+		sem_post(&inas_locked);
+		sem_post(&inas_read);
+		join(d);
+		goto out;
+	}
+	base = total_bw_of(top_cpu(1));	/* with D, without O */
+	if (pthread_create(&o, NULL, nps_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&inas_locked);
+		sem_post(&inas_read);
+		join(d);
+		goto out;
+	}
+	if (wait_for(1000, inas_locking && proc_state_of(inas_d_tid) == 'S' &&
+		     nps_o_tid && proc_state_of(nps_o_tid) == 'S')) {
+		ksft_print_msg("the owner did not sleep boosted\n");
+	} else {
+		err = set_deadline(nps_o_tid, 5 * NSEC_PER_MSEC, 2 * PERIOD);
+		if (!err)
+			with_o = total_bw_of(top_cpu(1));
+		if (!err)
+			err = set_other(nps_o_tid);
+		if (!err && sem_getvalue(&inas_out, &out))
+			out = -1;
+		if (err)
+			ksft_print_msg("the owner cannot change its parameters: %s\n",
+				       strerror(-err));
+		else if (out)
+			ksft_print_msg("the donor timed out before the change\n");
+		else if (sem_wait_for(&inas_out, 5000))
+			ksft_print_msg("the donor did not time out\n");
+		else {
+			while (now_ns() - nps_t0 < 115 * NSEC_PER_MSEC)
+				sleep_ns(NSEC_PER_MSEC);
+			early = total_bw_of(top_cpu(1));
+			while (now_ns() - nps_t0 < 145 * NSEC_PER_MSEC)
+				sleep_ns(NSEC_PER_MSEC);
+			late = total_bw_of(top_cpu(1));
+		}
+	}
+	sem_post(&inas_read);
+	pthread_join(d, &d_ret);
+	sem_post(&nps_wake);
+	pthread_join(o, &o_ret);
+	if (o_ret || d_ret || late < 0)
+		goto out;	/* a thread said why */
+	if (early != with_o) {
+		ksft_print_msg("total_bw %lld at 115 ms, %lld expected: %s\n", early,
+			       with_o, "O left before it repaid its debt");
+		goto out;
+	}
+	if (late != base) {
+		ksft_print_msg("total_bw %lld at 145 ms, %lld expected: %s\n", late,
+			       base, "O stayed after it repaid its debt");
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&inas_ready);
+	sem_destroy(&inas_locked);
+	sem_destroy(&inas_out);
+	sem_destroy(&inas_read);
+	sem_destroy(&nps_wake);
+	pi_fini();
+	return ret;
+}
+
 static _Atomic uint32_t rq_cond, rq_pi;
 static atomic_int rq_order, rq_w_rank, rq_x_rank, rq_x_locking;
 static _Atomic pid_t rq_w_tid, rq_x_tid;
@@ -2754,17 +2928,30 @@ 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, while a donor boosts the thread. The thread takes pi_lock and
+ *   wakes the donor up. The donor blocks on pi_lock. The thread then
+ *   changes its parameters, and unlocks.
+ * - 4: as 2, to a constrained deadline: 8ms in 20ms, every 100ms.
+ * - 5: the thread sleeps. The main thread changes it to 8ms in 20ms,
+ *   every 100ms.
+ * The new parameters are 10ms every 100ms, except in modes 4 and 5.
+ * 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);
@@ -2773,8 +2960,34 @@ 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 == 5) {
+		sem_post(&ret_ready);
+		sem_wait_sig(&ret_go);
+	} else if (mode == 4) {
+		err = set_constrained(0, 8 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	} else if (mode == 3) {
+		if (take_pi_lock())
+			return (void *)1;
+		sem_post(&owner_go);
+		t0 = now_ns();
+		while (!refill_donor_locking || proc_state_of(donor_tid) != 'S') {
+			if (now_ns() - t0 > NSEC_PER_SEC) {
+				ksft_print_msg("the donor did not block on the lock\n");
+				drop_pi_lock();
+				return (void *)1;
+			}
+		}
+		err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+		drop_pi_lock();
+	} 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)
@@ -2784,46 +2997,80 @@ 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 4 and 5. 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;
+	void *t_ret = NULL, *d_ret = NULL;
 	int err, ret = KSFT_PASS;
-	pthread_t t;
+	pthread_t t, d;
 
 	if (sem_init(&ret_ready, 0, 0) || sem_init(&ret_go, 0, 0)) {
 		ksft_print_msg("sem_init: %s\n", strerror(errno));
 		return KSFT_FAIL;
 	}
 	ret_first_period_ms = -1;
-	if (pthread_create(&t, NULL, returner, NULL)) {
+	if (mode == 3) {
+		/* The donor: a deadline task of 2ms every 10ms */
+		if (pi_init() || sem_init(&refill_donor_ready, 0, 0))
+			return KSFT_SKIP;
+		refill_donor_locking = 0;
+		donor_tid = 0;
+		if (pthread_create(&d, NULL, refill_donor, NULL)) {
+			ksft_print_msg("the donor thread could not start\n");
+			return KSFT_FAIL;
+		}
+		if (sem_wait_for(&refill_donor_ready, 5000) || donor_tid <= 0) {
+			ksft_print_msg("the donor is not ready\n");
+			sem_post(&owner_go);
+			join(d);
+			return KSFT_FAIL;
+		}
+	}
+	if (pthread_create(&t, NULL, returner, (void *)mode)) {
 		ksft_print_msg("the task thread could not start\n");
+		if (mode == 3) {
+			sem_post(&owner_go);
+			join(d);
+		}
 		return KSFT_FAIL;
 	}
-	if (sem_wait_for(&ret_ready, 5000)) {
-		/* The thread may get there late. Let it end. */
+	if (mode == 1 || mode == 5) {
+		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 == 5)
+			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 (mode == 3) {
+		if (t_ret)
+			sem_post(&owner_go);	/* the task never woke the donor up */
+		if (pthread_join(d, &d_ret) || d_ret)
+			ret = KSFT_FAIL;
+		pi_fini();
+		sem_destroy(&refill_donor_ready);
+	}
 	if (err) {
 		ksft_print_msg("pthread_join: %s\n", strerror(err));
 		ret = KSFT_FAIL;
@@ -2839,6 +3086,3008 @@ 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);
+}
+
+/*
+ * The same, for a task that changes its parameters while a donor boosts
+ * it. The donor is a deadline task of 2ms every 10ms. Its deadline is the
+ * earlier one, so the task runs on its own runtime while boosted. The
+ * unlock ends the boost. The runtime left must then be checked against
+ * the new parameters.
+ */
+static int change_boosted_new_params(void)
+{
+	return return_case(3);
+}
+
+/*
+ * 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(4);
+}
+
+/*
+ * 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(5);
+}
+
+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))
+
+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 */
+	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]);
+	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;
+	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 sem_t rb_donor_go;
+static atomic_int rb_abort, rb_donor_locking, rb_donor_done, rb_waiter_locking;
+static _Atomic pid_t rb_waiter_tid;
+static _Atomic long long rb_spin_ns;
+
+/*
+ * Run as the owner O of deboost_new_params_reboost(). Its comment has
+ * the steps. Store in rb_spin_ns the time that O's last spin, 20ms of CPU
+ * time, takes. Return NULL, or 1 on an error.
+ */
+static void *reboost_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	owner_tid = gettid_();
+	if (take_pi_lock())
+		return (void *)1;
+	owner_holds = 2;
+	sem_wait_sig(&owner_go);
+	if (rb_abort) {
+		drop_pi_lock();
+		return NULL;
+	}
+	err = set_deadline(0, 50 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner refused as a deadline task: %s\n",
+			       strerror(-err));
+		goto out;
+	}
+	sem_post(&rb_donor_go);
+	t0 = now_ns();
+	while (!rb_donor_locking || proc_state_of(donor_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not block on the lock\n");
+			err = -1;
+			goto out;
+		}
+	}
+	err = set_deadline(rb_waiter_tid, 2 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		goto out;
+	}
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner could not change: %s\n",
+			       strerror(-err));
+		goto out;
+	}
+	t0 = now_ns();
+	while (!rb_donor_done) {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not time out\n");
+			err = -1;
+			goto out;
+		}
+	}
+	t0 = now_ns();
+	spin_ns(20 * NSEC_PER_MSEC);
+	rb_spin_ns = now_ns() - t0;
+out:
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Run as the donor D of deboost_new_params_reboost(). Become a deadline
+ * task of 5ms every 50ms, and sleep until rb_donor_go. Then wait 20ms for
+ * pi_lock. Return NULL if the wait timed out or the case gave up, or 1
+ * otherwise.
+ */
+static void *reboost_donor(void *arg)
+{
+	struct timespec ts;
+	int err;
+
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD / 2);
+	if (err) {
+		ksft_print_msg("the donor refused as a deadline task: %s\n",
+			       strerror(-err));
+		donor_tid = -1;
+		return (void *)1;
+	}
+	donor_tid = gettid_();
+	sem_wait_sig(&rb_donor_go);
+	if (rb_abort) {
+		set_other(0);
+		return NULL;
+	}
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_nsec += 20 * 1000000L;
+	ts.tv_sec += ts.tv_nsec / 1000000000L;
+	ts.tv_nsec %= 1000000000L;
+	rb_donor_locking = 1;
+	err = pthread_mutex_timedlock(&pi_lock, &ts);
+	rb_donor_done = 1;
+	if (!err)
+		pthread_mutex_unlock(&pi_lock);
+	if (set_other(0))
+		ksft_print_msg("the donor cannot leave SCHED_DEADLINE\n");
+	if (err != ETIMEDOUT) {
+		ksft_print_msg("the donor: %s, not a timeout\n",
+			       err ? strerror(err) : "got pi_lock");
+		return (void *)1;
+	}
+	return NULL;
+}
+
+/*
+ * Run as the waiter W of deboost_new_params_reboost(). Wait for pi_lock
+ * as a fair task. The owner makes W a deadline task during the wait.
+ * Return NULL, or 1 on an error.
+ */
+static void *reboost_waiter(void *arg)
+{
+	rb_waiter_tid = gettid_();
+	rb_waiter_locking = 1;
+	if (take_pi_lock())
+		return (void *)1;
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+static int reboost_case(void);
+
+/*
+ * Check that a deboost boosts the owner again when the check of its new
+ * parameters moves its deadline after the one of its top waiter. The
+ * threads share the CPU of P:
+ *
+ *   owner O                     donor D               waiter W
+ *   fair                        5ms every 50ms        fair
+ *
+ *   takes pi_lock               sleeps
+ *                                                     blocks on pi_lock
+ *   becomes 50ms every 100ms
+ *   wakes D up
+ *                               preempts O
+ *                               waits 20ms for
+ *                                 pi_lock, boosts O
+ *   makes W 2ms every 100ms
+ *   changes itself to 5ms
+ *     every 100ms
+ *   spins
+ *                               times out: W is now
+ *                                 the top waiter
+ *   spins 20ms
+ *   unlocks
+ *                                                     takes pi_lock
+ *
+ * W gets its deadline after O does, so W's deadline is the later one.
+ * W blocks as a fair task: a deadline W could not preempt O to block.
+ *
+ * O has run about 20ms of its 50ms when D times out: 10ms more than its
+ * share. The deboost fits O's period to the new parameters. O keeps 5ms,
+ * and its next period starts once those 5ms and the 10ms of debt are
+ * paid at 5%: its deadline is about 300ms ahead. W's deadline is now the
+ * earlier one. W must boost O again. A boosted O is refilled from W, so
+ * its last spin takes about 20ms. Without the boost, O is throttled once
+ * its 5ms run out, until its new deadline. The case fails if the spin
+ * takes more than 50ms.
+ */
+static int deboost_new_params_reboost(void)
+{
+	return reboost_case();
+}
+
+/* Run deboost_new_params_reboost(). */
+static int reboost_case(void)
+{
+	void *o_ret = NULL, *d_ret = NULL, *w_ret = NULL;
+	int ret = KSFT_FAIL, have_d = 0, have_w = 0;
+	pthread_t o, d, w;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&rb_donor_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_FAIL;
+	}
+	donor_tid = 0;
+	rb_abort = 0;
+	rb_donor_locking = 0;
+	rb_donor_done = 0;
+	rb_waiter_locking = 0;
+	rb_waiter_tid = 0;
+	rb_spin_ns = -1;
+	if (pthread_create(&o, NULL, reboost_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		goto out_fini;
+	}
+	if (wait_for(5000, owner_holds) || owner_holds != 2) {
+		ksft_print_msg("the owner never took pi_lock\n");
+		goto out;
+	}
+	have_d = !pthread_create(&d, NULL, reboost_donor, NULL);
+	if (!have_d || wait_for(1000, donor_tid &&
+				   proc_state_of(donor_tid) == 'S') ||
+	    donor_tid < 0) {
+		ksft_print_msg("the donor never slept\n");
+		goto out;
+	}
+	have_w = !pthread_create(&w, NULL, reboost_waiter, NULL);
+	if (!have_w || wait_for(1000, rb_waiter_locking &&
+				   proc_state_of(rb_waiter_tid) == 'S')) {
+		ksft_print_msg("the waiter never waited on pi_lock\n");
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	/* On a failure, the owner and the donor end without the steps. */
+	rb_abort = ret != KSFT_PASS;
+	sem_post(&owner_go);
+	if (pthread_join(o, &o_ret))
+		ret = KSFT_FAIL;
+	sem_post(&rb_donor_go);
+	if (have_d && pthread_join(d, &d_ret))
+		ret = KSFT_FAIL;
+	if (have_w && pthread_join(w, &w_ret))
+		ret = KSFT_FAIL;
+	if (o_ret || d_ret || w_ret) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (ret == KSFT_PASS && rb_spin_ns > PERIOD / 2) {
+		ksft_print_msg("the spin took %lld ms: not boosted again\n",
+			       rb_spin_ns / (long long)NSEC_PER_MSEC);
+		ret = KSFT_FAIL;
+	}
+out_fini:
+	sem_destroy(&rb_donor_go);
+	pi_fini();
+	return ret;
+}
+
+static sem_t das_donor_ready, das_owner_locked;
+static atomic_int das_donor_locking;
+static _Atomic pid_t das_donor_tid;
+static _Atomic long long das_back_ms;
+
+/*
+ * Run as the donor D of deboost_asleep_new_params(). Become a deadline
+ * task of 1ms every 10ms. Once O holds pi_lock, wait 150ms for it. Return
+ * NULL if the wait timed out, or 1 otherwise.
+ */
+static void *das_donor(void *arg)
+{
+	struct timespec ts;
+	int err;
+
+	das_donor_tid = gettid_();
+	err = set_deadline(0, NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	sem_post(&das_donor_ready);
+	if (err) {
+		ksft_print_msg("the donor refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	if (sem_wait_for(&das_owner_locked, 5000)) {
+		ksft_print_msg("the owner did not take the lock\n");
+		set_other(0);
+		return (void *)1;
+	}
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_nsec += 150 * 1000000L;
+	ts.tv_sec += ts.tv_nsec / 1000000000L;
+	ts.tv_nsec %= 1000000000L;
+	das_donor_locking = 1;
+	err = pthread_mutex_timedlock(&pi_lock, &ts);
+	if (!err)
+		pthread_mutex_unlock(&pi_lock);
+	if (set_other(0))
+		ksft_print_msg("the donor cannot leave SCHED_DEADLINE\n");
+	if (err != ETIMEDOUT) {
+		ksft_print_msg("the donor: %s, not a timeout\n",
+			       err ? strerror(err) : "got pi_lock");
+		return (void *)1;
+	}
+	return NULL;
+}
+
+/*
+ * Run as the owner O of deboost_asleep_new_params(). Its comment has the
+ * steps. Store in das_back_ms the time at which O runs after its sleep.
+ * Return NULL, or 1 on an error.
+ */
+static void *das_owner(void *arg)
+{
+	struct timespec ts;
+	uint64_t t0, end;
+	int err;
+
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&das_owner_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&das_owner_locked);
+	while (!das_donor_locking || proc_state_of(das_donor_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not block on the lock\n");
+			err = -1;
+			goto out;
+		}
+	}
+	err = set_constrained(0, 9 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner could not change: %s\n", strerror(-err));
+		goto out;
+	}
+	end = t0 + 190 * 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)
+		;
+	das_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+out:
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Deboost a task that sleeps on a timer, after it changed its parameters
+ * while boosted. The threads share the CPU of P:
+ * 1. O becomes a deadline task of 10ms in 20ms, every 100ms, at 0ms. It
+ *    takes pi_lock.
+ * 2. D, a deadline task of 1ms every 10ms, waits 150ms for pi_lock. It
+ *    boosts O.
+ * 3. O changes itself to 9ms in 20ms, every 100ms. It sleeps until
+ *    190ms, holding pi_lock.
+ * 4. D times out at 150ms, while O sleeps.
+ * 5. O wakes up at 190ms. Its own period ended at 100ms. It must run at
+ *    once, in a new period.
+ *
+ * If the deboost checks O's new parameters while O sleeps, O starts a
+ * period at 150ms, with a deadline at 170ms. Its wakeup at 190ms is then
+ * between that deadline and the next period, at 250ms. It throttles O
+ * until 250ms. The case fails if O runs at 220ms or later.
+ */
+static int deboost_asleep_new_params(void)
+{
+	void *o_ret = NULL, *d_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t o, d;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&das_donor_ready, 0, 0) || sem_init(&das_owner_locked, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_FAIL;
+	}
+	das_donor_locking = 0;
+	das_donor_tid = 0;
+	das_back_ms = -1;
+	if (pthread_create(&d, NULL, das_donor, NULL)) {
+		ksft_print_msg("the donor thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&das_donor_ready, 5000)) {
+		sem_post(&das_owner_locked);
+		join(d);
+		goto out;
+	}
+	if (pthread_create(&o, NULL, das_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&das_owner_locked);
+		join(d);
+		goto out;
+	}
+	pthread_join(o, &o_ret);
+	pthread_join(d, &d_ret);
+	if (o_ret || d_ret || das_back_ms < 0)
+		goto out;	/* the thread said why */
+	if (das_back_ms >= 220) {
+		ksft_print_msg("O ran again at %lld ms, after its wakeup at 190\n",
+			       (long long)das_back_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&das_donor_ready);
+	sem_destroy(&das_owner_locked);
+	pi_fini();
+	return ret;
+}
+
+/* The kinds of owner_boost_case() */
+enum {
+	OB_GAP, OB_THROTTLED, OB_NEW_PARAMS, OB_RIVAL, OB_LONG,
+	OB_LATE_THROTTLE, OB_LATE_GAP,
+};
+
+static sem_t ob_locked, ob_go, ob_rival_go;
+static _Atomic unsigned long long ob_t0;
+static _Atomic long long ob_got_ms;
+static _Atomic pid_t ob_w_tid;
+static int ob_throttled, ob_kind;
+static atomic_int ob_w_locking;
+
+/*
+ * Run as the owner O of owner_boost_case(). Become a deadline task, take
+ * pi_lock, and act by ob_kind:
+ * - OB_GAP and OB_LATE_GAP: 10ms in 20ms, every 500ms. Sleep until 40ms.
+ *   O then wakes past its deadline, before its next period.
+ * - the other kinds: 10ms every 100ms. O runs out of runtime at 10ms,
+ *   holding the lock. Then:
+ *   - OB_THROTTLED and OB_RIVAL: spin 15ms of CPU time.
+ *   - OB_LATE_THROTTLE: sleep until W blocks on pi_lock, then spin 15ms.
+ *   - OB_NEW_PARAMS: spin 12ms. Change O to 9ms every 100ms, and W to 5ms
+ *     every 310ms. Then spin 3ms.
+ *   - OB_LONG: spin 12ms, then sleep until 250ms.
+ * Then unlock. Return NULL, or 1 on an error.
+ */
+static void *ob_owner(void *arg)
+{
+	struct timespec ts;
+	uint64_t end;
+	int err, bad = 0;
+
+	if (ob_throttled)
+		err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	else
+		err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+				      5 * PERIOD);
+	ob_t0 = now_ns();
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&ob_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&ob_locked);
+	if (ob_kind == OB_NEW_PARAMS) {
+		spin_ns(12 * NSEC_PER_MSEC);
+		err = set_deadline(0, 9 * NSEC_PER_MSEC, PERIOD);
+		if (!err)
+			err = set_deadline(ob_w_tid, 5 * NSEC_PER_MSEC,
+					   3 * PERIOD + 10 * NSEC_PER_MSEC);
+		if (err) {
+			ksft_print_msg("the owner could not change the parameters: %s\n",
+				       strerror(-err));
+			bad = 1;
+		}
+		spin_ns(3 * NSEC_PER_MSEC);
+	} else if (ob_kind == OB_LONG) {
+		spin_ns(12 * NSEC_PER_MSEC);
+		end = ob_t0 + 250 * 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)
+			;
+	} else if (ob_kind == OB_LATE_THROTTLE) {
+		end = now_ns();
+		while (!ob_w_locking || proc_state_of(ob_w_tid) != 'S') {
+			if (now_ns() - end > NSEC_PER_SEC) {
+				ksft_print_msg("the waiter did not block on the lock\n");
+				bad = 1;
+				break;
+			}
+			sleep_ns(NSEC_PER_MSEC);
+		}
+		spin_ns(15 * NSEC_PER_MSEC);
+	} else if (ob_throttled) {
+		spin_ns(15 * NSEC_PER_MSEC);
+	} else {
+		end = ob_t0 + 40 * 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)
+			;
+	}
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return bad ? (void *)1 : NULL;
+}
+
+/*
+ * Run as the waiter W of owner_boost_case(). Wait for ob_go. Then
+ * become a deadline task of 5ms every 300ms, or of 2ms every 10ms with
+ * OB_RIVAL, and take pi_lock. Store in ob_got_ms the time at which W gets
+ * it. Return NULL, or 1 on an error.
+ */
+static void *ob_waiter(void *arg)
+{
+	int err;
+
+	ob_w_tid = gettid_();
+	sem_wait_sig(&ob_go);
+	if (ob_kind == OB_RIVAL)
+		err = set_deadline(0, 2 * NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	else
+		err = set_deadline(0, 5 * NSEC_PER_MSEC, 3 * PERIOD);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		if (ob_kind == OB_RIVAL)
+			sem_post(&ob_rival_go);	/* release the rival */
+		return (void *)1;
+	}
+	if (ob_kind == OB_RIVAL)
+		sem_post(&ob_rival_go);
+	ob_w_locking = 1;
+	if (take_pi_lock()) {
+		set_other(0);
+		return (void *)1;
+	}
+	ob_got_ms = (now_ns() - ob_t0) / NSEC_PER_MSEC;
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as the rival C of pi_owner_throttled_rival(). Become a deadline
+ * task of 40ms in 60ms, every 100ms. Wait until W is about to block,
+ * then sleep until 13ms after O's start, and spin 40ms of CPU time.
+ * Return NULL, or 1 on an error.
+ */
+static void *ob_rival(void *arg)
+{
+	struct timespec ts;
+	uint64_t end;
+	int err;
+
+	err = set_constrained(0, 40 * NSEC_PER_MSEC, 60 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the rival refused as a deadline task: %s\n",
+			       strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&ob_rival_go);
+	end = ob_t0 + 13 * 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)
+		;
+	spin_ns(40 * NSEC_PER_MSEC);
+	if (set_other(0))
+		ksft_print_msg("the rival cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run an owner_boost case of @kind: ob_owner() and ob_waiter(), and
+ * ob_rival() with OB_RIVAL. W must get pi_lock within @limit_ms of O's
+ * start.
+ */
+static int owner_boost_case(int kind, int limit_ms)
+{
+	void *o_ret = NULL, *w_ret = NULL, *c_ret = NULL;
+	int throttled = kind != OB_GAP && kind != OB_LATE_GAP;
+	int ret = KSFT_FAIL;
+	pthread_t o, w, c;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (kind == OB_LONG) {
+		int 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");
+			pi_fini();
+			return KSFT_SKIP;
+		}
+	}
+	if (sem_init(&ob_locked, 0, 0) || sem_init(&ob_go, 0, 0) ||
+	    sem_init(&ob_rival_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_FAIL;
+	}
+	ob_throttled = throttled;
+	ob_kind = kind;
+	ob_got_ms = -1;
+	ob_w_locking = 0;
+	if (pthread_create(&w, NULL, ob_waiter, NULL)) {
+		ksft_print_msg("the waiter thread could not start\n");
+		goto out;
+	}
+	if (pthread_create(&o, NULL, ob_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&ob_go);
+		join(w);
+		goto out;
+	}
+	/* O holds pi_lock, and runs until it is throttled or asleep. */
+	if (sem_wait_for(&ob_locked, 5000)) {
+		sem_post(&ob_go);
+		join(o);
+		join(w);
+		goto out;
+	}
+	if (kind == OB_GAP)
+		sleep_ns(30 * NSEC_PER_MSEC);	/* O sleeps past its deadline */
+	if (kind == OB_RIVAL && pthread_create(&c, NULL, ob_rival, NULL)) {
+		ksft_print_msg("the rival thread could not start\n");
+		kind = OB_THROTTLED;
+		c_ret = (void *)1;
+	}
+	sem_post(&ob_go);
+	pthread_join(o, &o_ret);
+	pthread_join(w, &w_ret);
+	if (kind == OB_RIVAL)
+		pthread_join(c, &c_ret);
+	if (o_ret || w_ret || c_ret || ob_got_ms < 0)
+		goto out;	/* the thread said why */
+	if (ob_got_ms >= limit_ms) {
+		ksft_print_msg("the waiter got the lock at %lld ms, not before %d\n",
+			       (long long)ob_got_ms, limit_ms);
+		goto out;
+	}
+	if (kind == OB_LONG && klog_has(DL_LAG_MSG) == 1) {
+		ksft_print_msg("the deboost logged \"%s\"\n", DL_LAG_MSG);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&ob_locked);
+	sem_destroy(&ob_go);
+	sem_destroy(&ob_rival_go);
+	pi_fini();
+	return ret;
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner sleeps past its deadline:
+ * 1. O becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    takes pi_lock and sleeps until 40ms.
+ * 2. At 30ms, W becomes a deadline task of 5ms every 300ms and blocks on
+ *    pi_lock. O's deadline, 20ms, is the earlier one.
+ * 3. O wakes up at 40ms, between its deadline and its next period, at
+ *    500ms. The wakeup would throttle it until then.
+ *
+ * W must boost O: O cannot run on its own reservation. O then runs at
+ * 40ms and unlocks. The case fails if W gets pi_lock at 200ms or later.
+ */
+static int pi_owner_asleep_in_gap(void)
+{
+	return owner_boost_case(OB_GAP, 200);
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner ran out of runtime:
+ * 1. O becomes a deadline task of 10ms every 100ms, at 0ms. It takes
+ *    pi_lock and spins 15ms of CPU time. It is throttled at 10ms, until
+ *    100ms.
+ * 2. W then becomes a deadline task of 5ms every 300ms and blocks on
+ *    pi_lock. O's deadline, 100ms, is the earlier one.
+ *
+ * W must boost O: O cannot run on its own reservation. O then runs its
+ * last 5ms on W's runtime and unlocks. The case fails if W gets pi_lock
+ * at 60ms or later.
+ */
+static int pi_owner_throttled(void)
+{
+	return owner_boost_case(OB_THROTTLED, 60);
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner can still run on its own
+ * reservation, and the owner then runs out of runtime:
+ * 1. O becomes a deadline task of 10ms every 100ms, at 0ms. It takes
+ *    pi_lock, and sleeps until W blocks on it.
+ * 2. W becomes a deadline task of 5ms every 300ms and blocks on pi_lock.
+ *    O's deadline, 100ms, is the earlier one: W does not boost O.
+ * 3. O spins 15ms of CPU time. It runs out of runtime after 10ms, with
+ *    pi_lock.
+ *
+ * W must boost O then: O cannot run on its own reservation until 100ms.
+ * O then runs its last 5ms on W's runtime and unlocks. The case fails if
+ * W gets pi_lock at 60ms or later.
+ */
+static int pi_owner_runs_out_later(void)
+{
+	return owner_boost_case(OB_LATE_THROTTLE, 60);
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner sleeps before its
+ * deadline:
+ * 1. O becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    takes pi_lock and sleeps until 40ms.
+ * 2. W becomes a deadline task of 5ms every 300ms and blocks on pi_lock,
+ *    before 20ms. O's deadline, 20ms, is the earlier one: W does not
+ *    boost O.
+ * 3. O wakes up at 40ms, between its deadline and its next period, at
+ *    500ms. The wakeup would throttle it until then.
+ *
+ * W must boost O at that wakeup. O then runs at 40ms and unlocks. The
+ * case fails if W gets pi_lock at 200ms or later.
+ */
+static int pi_owner_wakes_in_gap_later(void)
+{
+	return owner_boost_case(OB_LATE_GAP, 200);
+}
+
+static _Atomic unsigned long long ho_t0;
+static _Atomic long long ho_w_got_ms;
+static _Atomic pid_t ho_o_tid, ho_w_tid;
+static atomic_int ho_o_locking, ho_w_locking, ho_w_queued;
+
+/*
+ * Run as the owner O of pi_owner_handed_off(). Become a deadline task of
+ * 10ms every 100ms, and take pi_lock, which A holds. Once O has it, set
+ * ho_w_queued if W still waits for it. Spin 15ms of CPU time and unlock.
+ * Return NULL, or 1 on an error.
+ */
+static void *ho_owner(void *arg)
+{
+	int err;
+
+	ho_o_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	ho_t0 = now_ns();
+	if (err) {
+		ksft_print_msg("the owner refused as a deadline task: %s\n",
+			       strerror(-err));
+		return (void *)1;
+	}
+	ho_o_locking = 1;
+	if (take_pi_lock()) {
+		set_other(0);
+		return (void *)1;
+	}
+	ho_w_queued = ho_w_got_ms < 0 && proc_state_of(ho_w_tid) == 'S';
+	spin_ns(15 * NSEC_PER_MSEC);
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as the waiter W of pi_owner_handed_off(). Become a deadline task of
+ * 5ms every 300ms and take pi_lock. Store in ho_w_got_ms the time at
+ * which W gets it. Return NULL, or 1 on an error.
+ */
+static void *ho_waiter(void *arg)
+{
+	int err;
+
+	ho_w_tid = gettid_();
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, 3 * PERIOD);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		return (void *)1;
+	}
+	ho_w_locking = 1;
+	if (take_pi_lock()) {
+		set_other(0);
+		return (void *)1;
+	}
+	ho_w_got_ms = (now_ns() - ho_t0) / NSEC_PER_MSEC;
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * A variant of pi_owner_runs_out_later(): the owner gets the lock by a
+ * hand-off, with the waiter already queued on it. A, the main thread of
+ * the case, is a SCHED_OTHER task:
+ * 1. A takes pi_lock.
+ * 2. O becomes a deadline task of 10ms every 100ms, at 0ms. It blocks on
+ *    pi_lock.
+ * 3. W becomes a deadline task of 5ms every 300ms. It blocks on pi_lock.
+ * 4. A unlocks. O's deadline, about 100ms, is the earlier one. So O gets
+ *    pi_lock, and W stays queued on it. O can still run on its own
+ *    reservation, so W does not boost it.
+ * 5. O spins 15ms of CPU time. It runs out of runtime after 10ms, with
+ *    pi_lock.
+ *
+ * W must boost O then: O cannot run on its own reservation until about
+ * 100ms. W blocked on pi_lock before O owned it. So the boost must find W
+ * among the waiters that O got with the lock. O then runs its last 5ms on
+ * W's runtime and unlocks. The case fails if W does not wait for pi_lock
+ * when O gets it, or if W gets pi_lock at 60ms or later.
+ */
+static int pi_owner_handed_off(void)
+{
+	void *o_ret = NULL, *w_ret = NULL;
+	int ret = KSFT_FAIL, w_blocked;
+	pthread_t o, w;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	ho_o_tid = 0;
+	ho_w_tid = 0;
+	ho_o_locking = 0;
+	ho_w_locking = 0;
+	ho_w_queued = 0;
+	ho_w_got_ms = -1;
+	if (take_pi_lock())
+		goto out;
+	w_blocked = 1;
+	if (pthread_create(&o, NULL, ho_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		drop_pi_lock();
+		goto out;
+	}
+	if (wait_for(1000, ho_o_locking && proc_state_of(ho_o_tid) == 'S')) {
+		ksft_print_msg("the owner did not block on the lock\n");
+		drop_pi_lock();
+		join(o);
+		goto out;
+	}
+	if (pthread_create(&w, NULL, ho_waiter, NULL)) {
+		ksft_print_msg("the waiter thread could not start\n");
+		drop_pi_lock();
+		join(o);
+		goto out;
+	}
+	if (wait_for(1000, ho_w_locking && proc_state_of(ho_w_tid) == 'S')) {
+		ksft_print_msg("the waiter did not block on the lock\n");
+		w_blocked = 0;
+	}
+	drop_pi_lock();
+	pthread_join(o, &o_ret);
+	pthread_join(w, &w_ret);
+	if (!w_blocked || o_ret || w_ret || ho_w_got_ms < 0)
+		goto out;	/* the thread said why */
+	if (!ho_w_queued) {
+		ksft_print_msg("the waiter did not wait when the owner got the lock\n");
+		goto out;
+	}
+	if (ho_w_got_ms >= 60) {
+		ksft_print_msg("the waiter got the lock at %lld ms, not before 60\n",
+			       (long long)ho_w_got_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	pi_fini();
+	return ret;
+}
+
+/*
+ * The owner of pi_owner_throttled() changes its parameters while boosted:
+ * 1. As in pi_owner_throttled(), O is throttled at 10ms, and W boosts it.
+ * 2. After 12ms of CPU time, O changes itself to 9ms every 100ms. Then it
+ *    changes W to 5ms every 310ms. This change of W walks the chain to O.
+ *    O has new parameters, so rt_mutex_setprio() deboosts O before it
+ *    compares O with W.
+ *
+ * O has used up its own runtime until 100ms, so W must boost it again.
+ * O then runs its last 3ms and unlocks. The case fails if W gets pi_lock
+ * at 60ms or later.
+ */
+static int pi_owner_held_new_params(void)
+{
+	return owner_boost_case(OB_NEW_PARAMS, 60);
+}
+
+/*
+ * A deadline task C competes with the boosted owner of
+ * pi_owner_throttled():
+ * 1. O becomes a deadline task of 10ms every 100ms, at 0ms. Its deadline
+ *    is 100ms. It takes pi_lock and spins 15ms of CPU time. It is
+ *    throttled at 10ms.
+ * 2. W then becomes a deadline task of 2ms every 10ms, and blocks on
+ *    pi_lock. Its deadline is about 20ms. W boosts O.
+ * 3. C becomes a deadline task of 40ms in 60ms, every 100ms. It wakes up
+ *    at 13ms, with a deadline of about 70ms, and spins 40ms.
+ *
+ * Boosted, O must run on W's deadlines, before C's. O then runs its last
+ * 5ms and unlocks. Refilled from its own deadline, O would get a deadline
+ * of 110ms. That is after C's, so O would wait for C. The case fails if W
+ * gets pi_lock at 35ms or later.
+ */
+static int pi_owner_throttled_rival(void)
+{
+	return owner_boost_case(OB_RIVAL, 35);
+}
+
+/*
+ * The owner of pi_owner_throttled() stays boosted past its own next
+ * period:
+ * 1. As in pi_owner_throttled(), O is throttled at 10ms, and W boosts it.
+ * 2. After 12ms of CPU time, O sleeps until 250ms with the lock. Its own
+ *    period ends at 100ms, during that sleep.
+ * 3. O unlocks at 250ms.
+ *
+ * The deboost must start a period of O's own. Putting back the period
+ * that ended at 100ms would make the next refill print "sched: DL
+ * replenish lagged too much". The case fails if that message is logged,
+ * or if W gets pi_lock at 400ms or later. It skips if the message was
+ * logged before: the kernel prints it once.
+ */
+static int pi_owner_held_long(void)
+{
+	return owner_boost_case(OB_LONG, 400);
+}
+
+/*
+ * The threads of reboost_loop_case(): rb_owner() for each owner, rb_waiter()
+ * and rb_victim(). Each owner holds its own lock in rb_lock[].
+ */
+#define RB_OWNERS	2	/* the most owners of a case */
+#define RB_JOBS		20	/* periods of the victim */
+#define RB_RUNTIME	(35 * NSEC_PER_MSEC)	/* of the victim */
+#define RB_PERIOD	(50 * NSEC_PER_MSEC)	/* of the victim */
+
+static pthread_mutex_t rb_lock[RB_OWNERS];
+static sem_t rb_locked, rb_ready, rb_go, rb_go_w;
+static atomic_int rb_stop, rb_release;
+static uint64_t rb_victim_ns, rb_waits;
+
+/*
+ * Run as an owner of reboost_loop_case(). Become a deadline task of 1ms
+ * every 3s, take rb_lock[@arg] and post rb_locked. Spin until rb_release
+ * is set, then unlock. Return NULL, or 1 on an error.
+ */
+static void *rb_owner(void *arg)
+{
+	long i = (long)arg;
+	int err = set_deadline(0, NSEC_PER_MSEC, 30 * PERIOD);
+
+	if (err) {
+		ksft_print_msg("an owner refused as a deadline task: %s\n",
+			       strerror(-err));
+		sem_post(&rb_locked);
+		return (void *)1;
+	}
+	err = pthread_mutex_lock(&rb_lock[i]);
+	sem_post(&rb_locked);
+	if (err) {
+		ksft_print_msg("an owner cannot take its lock: %s\n", strerror(err));
+		set_other(0);
+		return (void *)1;
+	}
+	while (!atomic_load(&rb_release))
+		;
+	err = pthread_mutex_unlock(&rb_lock[i]);
+	if (err)
+		ksft_print_msg("an owner cannot unlock: %s\n", strerror(err));
+	if (set_other(0))
+		ksft_print_msg("an owner cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Run as the waiter of reboost_loop_case(), with @arg owners. Become a
+ * deadline task of 1ms every 10ms, post rb_ready and wait for rb_go_w.
+ * Until rb_stop is set, wait 1ms for each lock in turn, and count the
+ * waits in rb_waits. Each wait boosts the owner, and must time out. Then
+ * set rb_release, and take each lock without a timeout: its owner runs
+ * on the boost and unlocks. Return NULL, or 1 on an error.
+ */
+static void *rb_waiter(void *arg)
+{
+	int n = (long)arg, i = 0, err, bad = 0;
+
+	err = set_deadline(0, NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		bad = 1;
+	}
+	sem_post(&rb_ready);
+	sem_wait_sig(&rb_go_w);
+	while (!bad && !atomic_load(&rb_stop)) {
+		struct timespec ts;
+
+		clock_gettime(CLOCK_REALTIME, &ts);
+		ts.tv_nsec += 1000000L;
+		ts.tv_sec += ts.tv_nsec / 1000000000L;
+		ts.tv_nsec %= 1000000000L;
+		err = pthread_mutex_timedlock(&rb_lock[i], &ts);
+		if (err != ETIMEDOUT) {
+			ksft_print_msg("a wait of 1ms for a lock: %s, not a timeout\n",
+				       err ? strerror(err) : "got it");
+			if (!err)
+				pthread_mutex_unlock(&rb_lock[i]);
+			bad = 1;
+			break;
+		}
+		rb_waits++;
+		i = (i + 1) % n;
+	}
+	atomic_store(&rb_release, 1);
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.47.3

Part of the diff is not shown here. View the raw message.

#58 lore raw

PATCH v11 43/43 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
#25 lore raw

Re: [PATCH v11 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] rtmutex: waiter->pi_se desynchronizes from owner->dl.pi_se after unlocking pi_lock --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] rtmutex: waiter->pi_se desynchronizes from owner->dl.pi_se after unlocking pi_lock
--

commit 20b64bd5f85400f14e722790295c12b998e0b8ee
Author: Mathieu Desnoyers <[email protected]>

rtmutex: Continue the chain walk when a waiter's deadline donor changes

This commit records a task's deadline donor in struct rt_mutex_waiter and includes it in the chain-walk termination check so that donor changes on a blocked task propagate to downstream lock owners even when the waiter's priority and deadline sort keys remain unchanged.

Quoted 25 lines
kernel/locking/rtmutex.c +6 -0
index 5a9534c715b84..c78dfe9c93fc5 100644
@@ -369,10 +369,12 @@ static __always_inline void
 waiter_update_prio(struct rt_mutex_waiter *waiter, struct task_struct *task)
 {
 	lockdep_assert_held(&waiter->lock->wait_lock);
+	lockdep_assert_held(&task->pi_lock);
 	lockdep_assert(RB_EMPTY_NODE(&waiter->tree.entry));
 
 	waiter->tree.prio = __waiter_prio(task);
 	waiter->tree.deadline = task->dl.deadline;
+	waiter->pi_se = task->dl.pi_se;
 }
 
 /*
@@ -433,6 +435,21 @@ static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left,
 	return 1;
 }
 
+/*
+ * Return true if @waiter is up to date with its task @task. Compare the
+ * sort keys and the deadline donor, which rt_mutex_setprio() copies from
+ * @task to the lock owner. A boost or a deboost of @task can change its

kernel/locking/rtmutex.c static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left, · line 451

Quoted 10 lines
kernel/locking/rtmutex.c +10 -0
+ * donor and leave its keys as they were. The owner must then get the new
+ * donor: the old one can exit. The caller holds @task->pi_lock, which
+ * protects @task->dl.pi_se. @waiter->pi_se is never dereferenced.
+ */
+static __always_inline bool
+rt_waiter_up_to_date(struct rt_mutex_waiter *waiter, struct task_struct *task)
+{
+	return rt_waiter_node_equal(&waiter->tree, task_to_waiter_node(task)) &&
+	       waiter->pi_se == task->dl.pi_se;
+}

[Severity: Medium]
Can waiter->pi_se get out of sync with the donor that rt_mutex_setprio() copies to the lock owner?

In rt_mutex_adjust_prio_chain(), waiter_update_prio() snapshots waiter->pi_se from task->dl.pi_se at [7], then drops task->pi_lock at [8] before taking owner->pi_lock and calling rt_mutex_adjust_prio() at [11]:

kernel/locking/rtmutex.c:rt_mutex_adjust_prio_chain() {
    ...
	waiter_update_prio(waiter, task);

	rt_mutex_enqueue(lock, waiter);
	...
	raw_spin_unlock(&task->pi_lock);
	put_task_struct(task);
	...
	task = get_task_struct(rt_mutex_owner(lock));
	raw_spin_lock(&task->pi_lock);

	/* [11] requeue the pi waiters if necessary */
	if (waiter == rt_mutex_top_waiter(lock)) {
		rt_mutex_dequeue_pi(task, prerequeue_top_waiter);
		waiter_clone_prio(waiter, task);
		rt_mutex_enqueue_pi(task, waiter);
		rt_mutex_adjust_prio(lock, task);
    ...
}

Because rt_mutex_adjust_prio() -> rt_mutex_setprio() reads pi_task->dl.pi_se directly from the task rather than from the waiter, a concurrent boost and deboost on an intermediate task M (holding L1 and L1', blocked on L2 owned by O, already boosted by deadline task H on L1') can update O->dl.pi_se to a new deadline waiter W on L1 while M's waiter w_M on L2 still records &H->dl:

CPU0 (walk for H on L1') CPU1 (W blocks on L1, then leaves)
------------------------ ----------------------------------
rt_mutex_adjust_prio_chain(M)
raw_spin_lock(&M->pi_lock)
[7] waiter_update_prio(w_M, M)

        w_M->pi_se = &H->dl
  [8] raw_spin_unlock(&M->pi_lock)
                                  task_blocks_on_rt_mutex(L1, W)
                                    raw_spin_lock(&M->pi_lock)
                                    rt_mutex_setprio(M, W)
                                      M->dl.pi_se = &W->dl
                                    raw_spin_unlock(&M->pi_lock)
  [10] raw_spin_lock(&O->pi_lock)
  [11] rt_mutex_adjust_prio(L2, O)
         rt_mutex_setprio(O, M)
           O->dl.pi_se = M->dl.pi_se
           /* O->dl.pi_se is &W->dl */
  [13] raw_spin_unlock(&O->pi_lock)
                                  remove_waiter(L1, W)
                                    raw_spin_lock(&M->pi_lock)
                                    rt_mutex_setprio(M, H)
                                      M->dl.pi_se = &H->dl
                                    raw_spin_unlock(&M->pi_lock)
                                  rt_mutex_adjust_prio_chain(M)
                                    raw_spin_lock(&M->pi_lock)
                                    rt_waiter_up_to_date(w_M, M)
                                      /* w_M->pi_se == M->dl.pi_se == &H->dl */
                                      goto out_unlock_pi;
                                  W exits

O refills from W->dl <-- use-after-free

Even with commit "sched/deadline: Hold a reference on the deadline donor of a boosted task" keeping W's task_struct alive, the chain walk still stops early at M and leaves O running on the departed donor W's parameters instead of H's.

Copying waiter->pi_se into waiter->pi_tree in waiter_clone_prio() and having rt_mutex_setprio() read the donor from the top pi_waiter (or holding the donor's pi_lock across the read) would keep waiter->pi_se and owner->dl.pi_se consistent.

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

Re: [PATCH v11 16/43] sched/deadline: Keep the last CPU a task has in its root domain

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] cgroup/cpuset: wrong v1 ancestor walk in cpuset_cpus_allowed_without() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] cgroup/cpuset: wrong v1 ancestor walk in cpuset_cpus_allowed_without()
--

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

sched/deadline: Keep the last CPU a task has in its root domain

This commit refuses CPU offline operations with -EBUSY when taking the CPU offline would move a SCHED_DEADLINE task out of the root domain that admitted its bandwidth.

Quoted 4 lines
kernel/cgroup/cpuset.c +0 -0
index 7bdb9e21a7edb..37d04b08996ec 100644

[ ... ]

Quoted 4 lines
kernel/cgroup/cpuset.c +0 -0
@@ -4312,6 +4334,292 @@ void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
 	spin_unlock_irqrestore(&callback_lock, flags);
 }
 

[ ... ]

Quoted 8 lines
kernel/cgroup/cpuset.c +8 -0
+bool cpuset_cpus_allowed_without(struct task_struct *tsk, int cpu,
+				 struct cpumask *pmask)
+{
+	const struct cpumask *possible = task_cpu_possible_mask(tsk);
+	struct cpuset *cs = task_cs(tsk), *from, *gone = NULL;
+
+	guard(rcu)();
+	if (!is_in_v2_mode()) {

kernel/cgroup/cpuset.c void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask) · line 4431

Quoted 10 lines
kernel/cgroup/cpuset.c +10 -0
+		/*
+		 * cgroup v1 moves the tasks of a cpuset left with no CPU to
+		 * the nearest ancestor that keeps one.
+		 */
+		for (from = cs; from; from = parent_cs(from)) {
+			cpumask_and(pmask, from->effective_cpus, cpu_active_mask);
+			cpumask_clear_cpu(cpu, pmask);
+			if (cpumask_intersects(pmask, possible))
+				break;
+		}

[Severity: Medium]
Should the cgroup v1 loop break on !cpumask_empty(pmask) instead of cpumask_intersects(pmask, possible)?

On cgroup v1, cpuset1_hotplug_update_tasks() only considers a cpuset empty and moves its tasks to an ancestor when cs->cpus_allowed becomes completely empty:

kernel/cgroup/cpuset-v1.c:cpuset1_hotplug_update_tasks() {
    ...
	is_empty = cpumask_empty(cs->cpus_allowed) ||
		   nodes_empty(cs->mems_allowed);
    ...
	if (is_empty)
		remove_tasks_in_empty_cpuset(cs);
}

On systems with asymmetric 32-bit support where task_cpu_possible_mask(tsk) is a subset of cpu_possible_mask, a cpuset can retain active 64-bit-only CPUs after the offline while having no CPUs left in possible. In that case cgroup v1 leaves the task in cs and falls back to select_fallback_rq(), whereas this loop walks up to parent_cs(from) and can return an ancestor's 32-bit-capable CPUs in pmask, allowing dl_task_leaves_span() to accept an offline that moves a deadline task to another root domain or reject a valid one with -EBUSY.

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

Re: [PATCH v11 25/43] sched/deadline: Count the 0-lag time from the next period

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: dl_time_to_zerolag() miscomputes 0-lag when deadline is 0 --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: dl_time_to_zerolag() miscomputes 0-lag when deadline is 0
--

commit 03d5dc8d2f6d0b382a7bed954bd1379667e09042
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Count the 0-lag time from the next period

This commit computes a deadline entity's 0-lag time relative to dl_next_period(dl_se) rather than dl_se->deadline so that tasks with constrained deadlines do not reach their 0-lag time prematurely.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 74b3c6b967eee..1d2dcf478f95d 100644

[ ... ]

kernel/sched/deadline.c static unsigned int dl_task_root_domain_cpu(struct task_struct *p); · line 641

Quoted 8 lines
kernel/sched/deadline.c +2 -2
@@ -633,12 +637,12 @@ static unsigned int dl_task_root_domain_cpu(struct task_struct *p);
  */
 static s64 dl_time_to_zerolag(struct sched_dl_entity *dl_se, struct rq *rq)
 {
-	/* Time to the deadline. Negative if the deadline has passed. */
-	s64 left = dl_se->deadline - rq_clock(rq);
+	/* Time to the next period. Negative if it has started. */
+	s64 left = dl_next_period(dl_se) - rq_clock(rq);

[Severity: Medium]
Can dl_time_to_zerolag() return a positive delay when dl_se->deadline is 0?

If a sleeping task with no active period (dl_se->deadline == 0 and dl_se->runtime == 0) is switched into SCHED_DEADLINE with a constrained deadline (dl_deadline < dl_period) and then switched back out while still asleep, switched_from_dl() -> task_non_contending() calls dl_time_to_zerolag(). Previously, dl_se->deadline - rq_clock(rq) was negative and the bandwidth was released immediately. With dl_next_period(), 0 - dl_deadline + dl_period evaluates to dl_period - dl_deadline; whenever rq_clock(rq) is smaller than that difference, left is non-negative and inactive_timer is armed, holding the task's bandwidth in root-domain total_bw and causing subsequent admission checks to fail with -EBUSY.

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

Re: [PATCH v11 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: select_fallback_rq() bypasses local NUMA node search - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: select_fallback_rq() bypasses local NUMA node search
- [Medium] sched/deadline: __set_cpus_allowed_ptr_locked() clobbers valid wake_cpu
--

commit 4af84b97f62357ff3460aae481348b8b367fe8d9
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Keep a task in the root domain that counts its bandwidth

This commit introduces dl_task_bw_span() and updates CPU selection paths during affinity changes, wakeups, CPU offline, and sched domain rebuilds to prefer CPUs within the root domain that accounts for a deadline task's bandwidth.

Quoted 20 lines
kernel/sched/core.c +12 -0
index 7615ba02d52b3..3dd42581cc177 100644
@@ -3264,6 +3264,27 @@ static int __set_cpus_allowed_ptr_locked(struct task_struct *p,
 			dest_cpu = ctx->dl_bw_cpu;
 		if (!task_on_rq_queued(p))
 			p->wake_cpu = dest_cpu;
+	} else {
+		const struct cpumask *span = dl_task_bw_span(p);
+		unsigned int cpu = nr_cpu_ids;
+
+		/*
+		 * No room was made for @p in another root domain. Keep @p
+		 * in the root domain that counts its bandwidth, if the new
+		 * mask holds one of its CPUs. Also wake a sleeping @p up
+		 * there. A wakeup during a rebuild of the sched domains has
+		 * no span to prefer.
+		 */
+		if (span && cpumask_test_cpu(dest_cpu, span))

kernel/sched/core.c static int __set_cpus_allowed_ptr_locked(struct task_struct *p, · line 3288

Quoted 10 lines
kernel/sched/core.c +9 -0
+			cpu = dest_cpu;
+		else if (span)
+			cpu = cpumask_first_and_and(cpu_valid_mask,
+						    ctx->new_mask, span);
+		if (cpu < nr_cpu_ids) {
+			dest_cpu = cpu;
+			if (!task_on_rq_queued(p))
+				p->wake_cpu = dest_cpu;
+		}
 	}

[Severity: Medium]
Does this overwrite p->wake_cpu for a sleeping deadline task even when its existing p->wake_cpu is still valid in ctx->new_mask and span?

dest_cpu is chosen earlier via cpumask_any_and_distribute(cpu_valid_mask, ctx->new_mask). Unlike a queued task (where affine_move_task() leaves p on task_cpu(p) if it remains in the new mask), a sleeping deadline task has p->wake_cpu unconditionally replaced with the pseudo-random dest_cpu whenever span is non-NULL, forcing an unnecessary migration on the next wakeup.

Only updating p->wake_cpu when it is not already in cpu_valid_mask, ctx->new_mask, and span would preserve wakeup locality.

Quoted 13 lines
kernel/sched/core.c +7 -0
@@ -3668,8 +3689,22 @@ static int select_fallback_rq(int cpu, struct task_struct *p)
 	int nid = cpu_to_node(cpu);
 	const struct cpumask *nodemask = NULL;
 	enum { cpuset, possible, fail } state = cpuset;
+	const struct cpumask *span;
+	bool span_forced = false;
 	int dest_cpu;
 
+	/*
+	 * Keep a deadline task in the root domain that counts its
+	 * bandwidth, if one of its CPUs is allowed and online.
+	 */
+	span = dl_task_bw_span(p);

kernel/sched/core.c static int select_fallback_rq(int cpu, struct task_struct *p) · line 3710

Quoted 10 lines
kernel/sched/core.c +7 -0
+	if (span) {
+		for_each_cpu_and(dest_cpu, span, p->cpus_ptr) {
+			if (is_cpu_allowed(p, dest_cpu))
+				return dest_cpu;
+		}
+	}
+
 	/*
 	 * If the node that the CPU is on has been offlined, cpu_to_node()
 	 * will return -1. There is no CPU on the node, and we should

[Severity: Medium]
Does this early return bypass the local NUMA node search in select_fallback_rq() for deadline tasks?

Because dl_task_bw_span(p) returns rd->span for any admitted deadline task outside a domain rebuild, scanning span & p->cpus_ptr in ascending CPU order and returning before the cpumask_of_node(nid) loop below skips same-node CPU selection on multi-node NUMA systems and always sends the task to the lowest-numbered allowed CPU in its root domain.

Checking cpumask_of_node(nid) intersected with span first when span is non-NULL would keep the task in its root domain while preserving NUMA locality.

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

Re: [PATCH v11 17/43] cgroup/cpuset: Refuse to take a deadline task out of its root domain

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] cgroup/cpuset: unnecessary hierarchy and task walks in dl_tasks_keep_*() - [Medium] cgroup/cpuset…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] cgroup/cpuset: unnecessary hierarchy and task walks in dl_tasks_keep_*()
- [Medium] cgroup/cpuset: dl_tasks_keep_without() omits pending CPUs for PRS_ISOLATED
--

commit 0cb8536a44f47c8f95c649627afa6a220c61e952
Author: Mathieu Desnoyers <[email protected]>

cgroup/cpuset: Refuse to take a deadline task out of its root domain

This commit refuses cpuset CPU mask updates and invalidates partitions that would move a deadline task out of the root domain accounting its bandwidth.

Quoted 4 lines
kernel/cgroup/cpuset.c +0 -0
index 37d04b08996ec..67b2429c0e22f 100644

[ ... ]

Quoted 40 lines
kernel/cgroup/cpuset.c +36 -0
@@ -1148,6 +1181,91 @@ static void effective_cpus_below(struct cpuset *cp, struct cpuset *from,
 	}
 }
 
+/*
+ * A scratch mask for dl_tasks_keep_without(). Its callers still need each
+ * mask of their struct tmpmasks after the call. Protected by
+ * cpuset_mutex.
+ */
+static cpumask_var_t dl_keep_cpus, dl_pending_cpus;
+
+/*
+ * Return false if a partition that takes the CPUs of @xcpus makes a
+ * deadline task leave the root domain that counts its bandwidth. A cpuset
+ * can hold CPUs of two root domains: with isolcpus="domain", or on cgroup
+ * v1 with sched_load_balance off. Such a task would run in a root domain
+ * that did not admit it.
+ *
+ * @root is the partition root that gives the CPUs. @part is the cpuset
+ * that takes them. In the same change, @part can give the CPUs of @gives
+ * back to @root. @gives is NULL if it gives none back.
+ *
+ * Work out the new CPUs of each cpuset of @root from the top down, as
+ * update_cpumasks_hier() does, down to the next partition roots. If
+ * @enable, @part becomes a partition root. Then do the same for its own
+ * cpusets, starting from the active CPUs of @xcpus.
+ */
+static bool dl_tasks_keep_without(struct cpuset *root, struct cpuset *part,
+				  const struct cpumask *xcpus,
+				  const struct cpumask *gives, bool enable)
+{
+	struct cpumask *new_cpus = dl_keep_cpus, *pending = NULL;
+	struct cgroup_subsys_state *pos_css;
+	struct cpuset *cp;
+	bool keep = true;
+
+	lockdep_assert_cpuset_lock_held();
+	/*
+	 * The CPUs of @root can have changed before the rebuild of the
+	 * sched domains, which ends the change. Then the root domain of a

kernel/cgroup/cpuset.c static void effective_cpus_below(struct cpuset *cp, struct cpuset *from, · line 1229

Quoted 10 lines
kernel/cgroup/cpuset.c +10 -0
+	 * task of @root does not span them yet. The rebuild gives the CPUs
+	 * of a root partition to one root domain.
+	 */
+	if (root->partition_root_state == PRS_ROOT) {
+		pending = dl_pending_cpus;
+		cpumask_copy(pending, root->effective_cpus);
+		if (root == &top_cpuset)
+			cpumask_and(pending, pending,
+				    housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
+	}

[Severity: Medium]
Should pending also be populated when root->partition_root_state is PRS_ISOLATED (or via is_partition_valid(root))?

An isolated partition root can have an invalid child isolated partition and hold deadline tasks counted in def_root_domain. When that isolated parent grows to include a new CPU before rebuild_sched_domains_locked() runs at the end of the change, def_root_domain.span does not include the new CPU yet. Because pending is left NULL here, re-evaluating the child during update_cpumasks_hier() -> update_parent_effective_cpumask() rejects the child with PERR_DLTASK even though the rebuild will attach the parent's new CPU to def_root_domain.

Quoted 10 lines
kernel/cgroup/cpuset.c +10 -0
+	rcu_read_lock();
+	cpuset_for_each_descendant_pre(cp, pos_css, root) {
+		if (cp == part || (cp != root && is_partition_valid(cp))) {
+			pos_css = css_rightmost_descendant(pos_css);
+			continue;
+		}
+		/* The CPUs that @root has after the change. */
+		cpumask_copy(new_cpus, root->effective_cpus);
+		if (gives) {
+			cpumask_or(new_cpus, new_cpus, gives);

kernel/cgroup/cpuset.c static void effective_cpus_below(struct cpuset *cp, struct cpuset *from, · line 1249

Quoted 10 lines
kernel/cgroup/cpuset.c +10 -0
+			cpumask_and(new_cpus, new_cpus, cpu_active_mask);
+		}
+		cpumask_andnot(new_cpus, new_cpus, xcpus);
+		effective_cpus_below(cp, root, new_cpus);
+		if (cpumask_equal(cp->effective_cpus, new_cpus))
+			continue;
+		keep = dl_tasks_keep_cpus(cp, new_cpus, pending);
+		if (!keep)
+			break;
+	}

[Severity: Medium]
Does dl_tasks_keep_without() (and dl_tasks_keep_root_domain() below) walk the cpuset hierarchy and iterate every task in affected cpusets even when no deadline tasks hold bandwidth or admission control is disabled?

Commit "sched/deadline: Keep the last CPU a task has in its root domain" earlier in this series guards dl_cpu_last_of_task() with !dl_bandwidth_enabled() || !atomic_read(&dl_nr_bw_tasks), whereas here dl_bandwidth_enabled() is only checked per task inside dl_task_keeps_root_domain() after css_task_iter has already locked css_set_lock and pinned each task, and dl_nr_bw_tasks is not checked.

In addition, when cpumask_equal(cp->effective_cpus, new_cpus) is true in either function, continuing without advancing pos_css = css_rightmost_descendant(pos_css) visits all descendants of an unchanged subtree even though their effective_cpus cannot change either.

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

Re: [PATCH v11 26/43] sched/deadline: Keep a departing constrained task until its next period

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: dl_task_timer() advances period before inactive_task_timer() - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: dl_task_timer() advances period before inactive_task_timer()
- [Medium] sched/deadline: HRTIMER_RESTART in inactive_task_timer() races with cancel
--

commit 43e71343c7049144c9877a7ba7fddb15005d58e2
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Keep a departing constrained task until its next period

This commit keeps a departing constrained SCHED_DEADLINE task's bandwidth and deadline until the later of its 0-lag time and its next period in task_non_contending() and inactive_task_timer().

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 1d2dcf478f95d..11774b3b9fe93 100644

[ ... ]

kernel/sched/deadline.c static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer) · line 2625

Quoted 13 lines
kernel/sched/deadline.c +9 -0
@@ -2598,6 +2614,25 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 	if (dl_server(dl_se))
 		goto no_task;
 
+	/*
+	 * A constrained task which has left the class keeps its bandwidth
+	 * and its deadline until its next period, as in
+	 * task_non_contending(). This timer may have been armed for the
+	 * 0-lag time while the task was still in the class.
+	 */
+	if (!dl_task(p) && READ_ONCE(p->__state) != TASK_DEAD &&
+	    !dl_is_implicit(dl_se)) {
+		s64 left = dl_next_period(dl_se) - rq_clock(rq);

[Severity: Medium]
Can dl_task_timer() advance dl_se->deadline before inactive_task_timer() computes dl_next_period(dl_se), holding the departed task's bandwidth for an extra period?

When a constrained task is throttled before leaving SCHED_DEADLINE, dl_se->dl_timer remains armed for the end of the departure period while dl_se->inactive_timer is armed for max(0-lag time, dl_next_period(dl_se)). When dl_task_timer() fires at the period boundary while !dl_task(p), it replenishes the entity:

kernel/sched/deadline.c:dl_task_timer() {
    ...
	if (!dl_task(p)) {
		if (dl_se->dl_throttled && !is_dl_boosted(dl_se)) {
			sched_clock_tick();
			update_rq_clock(rq);
			replenish_dl_entity(dl_se);
		}
		goto unlock;
	}
    ...
}

replenish_dl_entity() adds dl_se->dl_period to dl_se->deadline until dl_se->runtime > 0. When inactive_task_timer() then runs at the period boundary (or later at the 0-lag time after an overrun), dl_next_period() is computed from the replenished dl_se->deadline, so left > 0 and inactive_task_timer() restarts for another full period instead of releasing the task's bandwidth and clearing its parameters. If the task re-enters SCHED_DEADLINE during that extra period after the advanced deadline, dl_check_constrained_dl() also throttles it until the end of the second period.

kernel/sched/deadline.c static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer) · line 2634

Quoted 9 lines
kernel/sched/deadline.c +9 -0
+
+		if (left > 0) {
+			ktime_t at = ktime_add_ns(hrtimer_cb_get_time(timer), left);
+
+			hrtimer_set_expires(timer, at);
+			task_rq_unlock(rq, p, &rf);
+			return HRTIMER_RESTART;
+		}
+	}

[Severity: Medium]
Can returning HRTIMER_RESTART after task_rq_unlock() race with cancel_inactive_timer() in switched_to_dl() and leave inactive_timer queued after the task returns to SCHED_DEADLINE?

cancel_dl_timer() assumes that when hrtimer_try_to_cancel() returns -1, the running callback will finish with HRTIMER_NORESTART and drop the task reference. Because __run_hrtimer() only re-acquires cpu_base->lock and re-enqueues the timer after inactive_task_timer() returns, another CPU can run switched_to_dl() in between:

CPU0 CPU1
__run_hrtimer()
inactive_task_timer()

    hrtimer_set_expires(timer, at)
    task_rq_unlock(rq, p, &rf)
                                      __sched_setscheduler()
                                        task_rq_lock(p, &rf)
                                        switched_to_dl()
                                          cancel_inactive_timer(&p->dl)
                                            hrtimer_try_to_cancel() -> -1
                                        task_rq_unlock(rq, p, &rf)
    return HRTIMER_RESTART

raw_spin_lock(&cpu_base->lock)
enqueue_hrtimer(timer, base, ...) <-- queued while p is in DL

p is then back in SCHED_DEADLINE with dl_non_contending == 0 while hrtimer_active(&p->dl.inactive_timer) is true. If p blocks or leaves SCHED_DEADLINE before that stale timer fires, task_non_contending() sees hrtimer_active(&dl_se->inactive_timer) and immediately subtracts running_bw or releases the task's bandwidth and clears its deadline before the 0-lag time.

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

Re: [PATCH v11 34/43] sched/deadline: Cancel the replenishment timer with the parameters

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: dl_task_timer() extends departed constrained task by a period --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: dl_task_timer() extends departed constrained task by a period
--

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

sched/deadline: Cancel the replenishment timer with the parameters

This commit cancels a task's deadline replenishment timer alongside clearing its deadline parameters in task_non_contending() and inactive_task_timer().

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index c59953e80b1a9..828923a771076 100644

[ ... ]

kernel/sched/deadline.c static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer) · line 2902

Quoted 8 lines
kernel/sched/deadline.c +1 -0
@@ -2895,6 +2896,7 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 		}
 
 		dl_task_release_bw(p);
+		cancel_replenish_timer(dl_se);
 		__dl_clear_params(dl_se);
 
 		goto unlock;

[Severity: Medium]
Can dl_task_timer() fire before inactive_task_timer() at dl_next_period(dl_se) for a departed constrained-deadline task, pushing its bandwidth release and parameter reset out by an extra period?

When a constrained-deadline task is throttled without a runtime overrun (for example via sched_yield()), start_dl_timer() queues dl_se->dl_timer for dl_next_period(dl_se). If the task then leaves SCHED_DEADLINE, task_non_contending() or inactive_task_timer() queues dl_se->inactive_timer for that same dl_next_period(dl_se) timestamp without cancelling dl_timer. Because dl_timer was queued in the hrtimer tree first, it fires first at dl_next_period(dl_se):

kernel/sched/deadline.c:dl_task_timer() {
    ...
	if (!dl_task(p)) {
		if (dl_se->dl_throttled && !is_dl_boosted(dl_se)) {
			sched_clock_tick();
			update_rq_clock(rq);
			replenish_dl_entity(dl_se);
		}
		goto unlock;
	}
    ...
}

replenish_dl_entity() advances dl_se->deadline by dl_period. When inactive_task_timer() runs right after, it sees dl_next_period(dl_se) - rq_clock(rq) == dl_period > 0 and returns HRTIMER_RESTART instead of reaching dl_task_release_bw(), cancel_replenish_timer(), and __dl_clear_params():

kernel/sched/deadline.c:inactive_task_timer() {
    ...
	if (!dl_task(p) && READ_ONCE(p->__state) != TASK_DEAD &&
	    !dl_is_implicit(dl_se)) {
		s64 left = dl_next_period(dl_se) - rq_clock(rq);

		if (left > 0) {
			ktime_t at = ktime_add_ns(hrtimer_cb_get_time(timer), left);

			hrtimer_set_expires(timer, at);
			task_rq_unlock(rq, p, &rf);
			return HRTIMER_RESTART;
		}
	}
    ...
}

The departed task's bandwidth remains locked in dl_b->total_bw for an extra period, and if the task returns to SCHED_DEADLINE after the phantom deadline it is throttled with zero runtime until that extra period ends.

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

Re: [PATCH v11 31/43] sched/deadline: Restore the owner's period at a deboost out of the class

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: missing throttle after held boost ends in switched_from_dl() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: missing throttle after held boost ends in switched_from_dl()
--

commit 7695498ee5152a5e36e39a21aef4b92a39936d61
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Restore the owner's period at a deboost out of the class

This commit restores the lock owner's own deadline and runtime parameters in switched_from_dl() when a priority-inheritance boost ends as the task leaves SCHED_DEADLINE, and recalculates the 0-lag inactive timer from the restored parameters.

Quoted 13 lines
kernel/sched/deadline.c +5 -0
index 4d46d1c9c6981..5d1d4ea288788 100644
@@ -4802,6 +4802,22 @@ void dl_clear_root_domains(void)
 
 static void switched_from_dl(struct rq *rq, struct task_struct *p)
 {
+	bool held = dl_end_held_boost(&p->dl);
+	bool own_period = held || (p->dl.dl_runtime && p->dl.dl_donor_refill);
+
+	/*
+	 * After a refill from the donor, the runtime and deadline are the

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

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	 * donor's. task_non_contending() would mix them with the task's own
+	 * dl_runtime and dl_period. So give the task values of its own first,
+	 * as dl_deboost() does. After a held boost, dl_end_held_boost() above
+	 * has put back the saved ones. A task with nothing saved starts a
+	 * period of its own. Its 0-lag time is then now. A constrained task
+	 * still keeps its bandwidth until its next period: see
+	 * task_non_contending().
+	 */
+	if (own_period && !held)
+		dl_start_own_period(&p->dl);

[Severity: Medium]
Should switched_from_dl() also throttle p->dl and arm p->dl.dl_timer when held is true and p->dl.runtime <= 0, the way dl_deboost() does?

When a task exhausts its own runtime while boosted, replenish_dl_entity() clears dl_throttled and dl_hold_refilled_boost() saves own_runtime = 0. If the task leaves SCHED_DEADLINE at the deboost before own_deadline, dl_end_held_boost() restores p->dl.deadline = own_deadline and p->dl.runtime = 0, leaving p->dl.dl_throttled == 0.

If the task switches back to SCHED_DEADLINE before p->dl.deadline, enqueue_dl_entity() sees dl_throttled == 0 and a deadline still in the future, so it enqueues the task onto dl_rq with runtime == 0 and lets it run past its reserved budget in the current period.

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

Re: [PATCH v11 30/43] sched/deadline: Start a period for a task that enters the class blocked

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: missing zero-deadline check in switched_to_dl() - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: missing zero-deadline check in switched_to_dl()
- [Medium] sched/deadline: dl_boost_blocked() skips tasks with non-zero dl_deadline
- [Medium] sched/deadline: switched_to_dl() skips donor period when throttled task is boosted
--

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

sched/deadline: Start a period for a task that enters the class blocked

This commit starts a deadline period for a task blocked on an rt_mutex when it enters SCHED_DEADLINE via switched_to_dl() or receives a new priority-inheritance donor via dl_boost_blocked(), so that the rt_mutex chain walk sorts its waiter with a current deadline rather than 0.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 5ec1c5eaf7647..4d46d1c9c6981 100644

[ ... ]

Quoted 17 lines
kernel/sched/deadline.c +13 -0
@@ -1301,6 +1312,30 @@ static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
 	trace_sched_dl_replenish_tp(dl_se, cpu_of(rq), dl_get_type(dl_se, rq));
 }
 
+#ifdef CONFIG_RT_MUTEXES
+/*
+ * Start a period from the new donor of @p, if @p has no reservation of its
+ * own and waits on an rt_mutex. The enqueue does this for a queued task, in
+ * replenish_dl_entity(). A blocked task is not enqueued, but the chain walk
+ * copies its deadline into its waiter.
+ *
+ * Call it only when the donor changes. A new period changes the deadline,
+ * so the chain walk finds the waiter out of date and goes on. In a ww_mutex
+ * cycle, a new period at each step would never let the walk stop.
+ *
+ * The caller holds the rq lock and the pi_lock of @p, and has updated the
+ * rq clock.

kernel/sched/deadline.c static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se, · line 1337

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+ */
+void dl_boost_blocked(struct task_struct *p)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+
+	if (!dl_se->dl_deadline && !dl_se->dl_throttled &&
+	    dl_task_pi_blocked(p))
+		replenish_dl_new_period(dl_se, task_rq(p));
+}
+#endif

[Severity: Medium]
Can dl_boost_blocked() leave an expired p->dl.deadline in place when a blocked task still has a non-zero dl_se->dl_deadline?

When a SCHED_DEADLINE task leaves the class before its 0-lag time, switched_from_dl() leaves dl_se->dl_deadline and dl_se->deadline non-zero until inactive_timer fires. If that task holds an rt_mutex, blocks on a second rt_mutex, and gets boosted back into dl_sched_class before dl_se->deadline passes, switched_to_dl() cancels inactive_timer (so __dl_clear_params() never clears dl_se->dl_deadline) and does not start a new period. If a second deadline donor with an earlier deadline boosts the task after dl_se->deadline has passed, dl_boost_blocked() returns early because dl_se->dl_deadline is non-zero, and the chain walk requeues the waiter with the expired dl_se->deadline ahead of waiters with current deadlines.

Quoted 16 lines
kernel/sched/deadline.c +12 -0
@@ -4866,6 +4901,26 @@ static void switched_to_dl(struct rq *rq, struct task_struct *p)
 	if (!task_on_rq_queued(p)) {
 		add_rq_bw(&p->dl, &rq->dl);
 
+		/*
+		 * The chain walk sorts the waiter of a task by its deadline,
+		 * before the wakeup sets the task up. A task new to the class
+		 * has a deadline of 0, which goes before every real one. So
+		 * start a new period now for a task that waits on an
+		 * rt_mutex, as setup_new_dl_entity() does at an enqueue.
+		 *
+		 * A task that comes back to the class before its 0-lag time
+		 * keeps its deadline. For a constrained task, that deadline
+		 * can have passed before its next period. As
+		 * dl_check_constrained_dl() does, leave such a task alone
+		 * unless it is boosted. Its wakeup throttles it until its

kernel/sched/deadline.c static void switched_to_dl(struct rq *rq, struct task_struct *p) · line 4925

Quoted 10 lines
kernel/sched/deadline.c +8 -0
+		 * next period.
+		 */
+		if (dl_task_pi_blocked(p) && !p->dl.dl_throttled &&
+		    dl_time_before(p->dl.deadline, rq_clock(rq)) &&
+		    (is_dl_boosted(&p->dl) ||
+		     !dl_time_before(rq_clock(rq), dl_next_period(&p->dl))))
+			replenish_dl_new_period(&p->dl, rq);
+
 		return;
 	}

[Severity: Medium]
Does switched_to_dl() skip replenish_dl_new_period() when a task with p->dl.deadline == 0 enters SCHED_DEADLINE with a constrained reservation while blocked on an rt_mutex?

__setparam_dl() writes p->dl.dl_deadline and p->dl.dl_period before switched_to_dl() runs. When p->dl.deadline is 0, dl_next_period(&p->dl) evaluates to dl_period - dl_deadline. If rq_clock(rq) < dl_period - dl_deadline, dl_time_before(rq_clock(rq), dl_next_period(&p->dl)) is true, so switched_to_dl() treats the never-initialized deadline as being in a constrained gap and leaves p->dl.deadline at 0 for the rt_mutex chain walk.

In addition, if a blocked task returning to SCHED_DEADLINE before its 0-lag time changes its dl_deadline or dl_period via sched_setattr(), dl_next_period(&p->dl) mixes the old p->dl.deadline with the newly overwritten p->dl.dl_deadline and p->dl.dl_period. Even after the later commit "sched/deadline: Keep the debt of a task across a change of parameters" replaces the dl_next_period() check with dl_in_constrained_gap(), dl_in_constrained_gap() still returns true when deadline == 0 and period_start == 0 while now < dl_period unless !p->dl.deadline is checked first.

[Severity: Medium]
Does the !p->dl.dl_throttled check in switched_to_dl() also prevent a throttled departed task from receiving a donor period when it is boosted back into SCHED_DEADLINE?

If a constrained SCHED_DEADLINE task exhausts its runtime (p->dl.dl_throttled = 1), switches to SCHED_OTHER before its next period, and blocks on an rt_mutex while holding another rt_mutex, a PI boost back into dl_sched_class after p->dl.deadline has passed sees p->dl.dl_throttled == 1 in switched_to_dl() and skips replenish_dl_new_period(). The chain walk then queues the waiter with the expired p->dl.deadline instead of the donor's deadline, and on unlock enqueue_task_dl() clears dl_throttled because is_dl_boosted(&p->dl) is true, letting the task run immediately ahead of earlier-deadline waiters.

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

Re: [PATCH v11 28/43] sched/deadline: Restore the owner's period at a deboost in the class

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] sched/deadline: missing dl_note_donor_refill() in replenish_dl_entity() - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] sched/deadline: missing dl_note_donor_refill() in replenish_dl_entity()
- [Medium] sched/deadline: dl_note_donor_refill() holds boost when deadline is 0
- [Medium] sched/deadline: running_bw under-accounting in dl_deboost() for blocked task
- [Medium] sched/deadline: dl_deboost() starts or arms period for sleeping task
--

commit 9f6872fae6d8bfd66c95f630e6a2c4067df9ded7
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Restore the owner's period at a deboost in the class

This commit saves a boosted task's own deadline and remaining runtime on its first donor replenishment and restores or restarts its own period when it is deboosted while staying in the deadline class.

Quoted 74 lines
kernel/sched/deadline.c +59 -0
index 172fb2811d4a0..100cb4b5fdb6d 100644
@@ -83,6 +83,53 @@ static inline int on_dl_rq(struct sched_dl_entity *dl_se)
 	return !RB_EMPTY_NODE(&dl_se->rb_node);
 }
 
+/*
+ * Start a period of the reservation of @dl_se now. The caller holds the rq
+ * lock and has updated the rq clock.
+ */
+static inline void dl_start_own_period(struct sched_dl_entity *dl_se)
+{
+	dl_se->deadline = rq_clock(rq_of_dl_se(dl_se)) + dl_se->dl_deadline;
+	dl_se->runtime = dl_se->dl_runtime;
+}
+
+/*
+ * Put back the deadline and runtime saved when the boost was held, by
+ * dl_hold_refilled_boost(). If the task's own next period has started
+ * since, start a period of its own instead. Return true if the boost was
+ * held. The caller holds the rq lock and has updated the rq clock.
+ */
+static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
+{
+	u64 now = rq_clock(rq_of_dl_se(dl_se));
+	u64 next = dl_se->own_deadline - dl_se->dl_deadline + dl_se->dl_period;
+
+	if (!dl_se->dl_boost_held)
+		return false;
+	if (dl_time_before(now, next)) {
+		dl_se->deadline = dl_se->own_deadline;
+		dl_se->runtime = dl_se->own_runtime;
+		/*
+		 * Past its own deadline, the task is in its constrained gap:
+		 * it waits for its own next period. Give back no runtime, so
+		 * that dl_deboost() throttles it. Before its deadline,
+		 * dl_hold_refilled_boost() can keep runtime left, from a
+		 * wakeup refill. Cap it at what the task's own density allows
+		 * until its deadline, as update_dl_revised_wakeup() does.
+		 */
+		if (!dl_time_before(now, dl_se->deadline))
+			dl_se->runtime = 0;
+		else if (dl_se->runtime > 0)
+			dl_se->runtime = min_t(s64, dl_se->runtime,
+					       (dl_se->dl_density *
+						(dl_se->deadline - now)) >> BW_SHIFT);
+	} else {
+		dl_start_own_period(dl_se);
+	}
+	dl_se->dl_donor_refill = 0;
+	return true;
+}
+
 #ifdef CONFIG_RT_MUTEXES
 static inline struct sched_dl_entity *pi_of(struct sched_dl_entity *dl_se)
 {
@@ -93,12 +140,104 @@ static inline bool is_dl_boosted(struct sched_dl_entity *dl_se)
 {
 	return pi_of(dl_se) != dl_se;
 }
+
+static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se);
+
+/*
+ * Record that a replenishment changes the runtime of @dl_se while it is
+ * boosted. At the first refill, dl_hold_refilled_boost() saves the
+ * task's own deadline and runtime. Call this before the replenishment
+ * adds runtime or moves the deadline. A task with no parameters of its
+ * own at the first refill has no period to save. Later refills of the
+ * same boost save nothing, even if the task gets parameters meanwhile.
+ */
+static inline void dl_note_donor_refill(struct sched_dl_entity *dl_se)

kernel/sched/deadline.c static inline bool is_dl_boosted(struct sched_dl_entity *dl_se) · line 164

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+{
+	bool first;
+
+	if (!is_dl_boosted(dl_se))
+		return;
+	first = !dl_se->dl_donor_refill;
+	dl_se->dl_donor_refill = 1;
+	if (first && dl_se->dl_runtime && !dl_se->dl_boost_held)
+		dl_hold_refilled_boost(dl_se);
+}

[Severity: Medium]
Can dl_note_donor_refill() call dl_hold_refilled_boost() when dl_se->deadline is still 0?

If an rt_mutex owner is boosted while sleeping on a non-PI waitqueue and is given SCHED_DEADLINE parameters via sched_setattr() before waking up, __setparam_dl() sets dl_se->dl_runtime > 0 while leaving dl_se->deadline at 0 because the task is not queued. When the task wakes up while still boosted, update_dl_entity() -> replenish_dl_new_period() -> dl_note_donor_refill() sees dl_se->dl_runtime != 0 and calls dl_hold_refilled_boost(), saving own_deadline = 0 and own_runtime = 0 with dl_boost_held = 1 even though the task has never started a period of its own.

At deboost, if dl_time_before(now, next) holds in dl_end_held_boost(), it restores dl_se->deadline = 0 and dl_se->runtime = 0 and throttles the task instead of starting its first own period. With commit "sched/deadline:
Keep the debt of a task across a change of parameters" later in this series, a subsequent sched_setattr() while running in this held boost sees own_runtime == 0 and starts the task's own period while it is still boosted, consuming its own deadline window while running for the donor. Also, prior to commit "sched/deadline: Boost an owner that cannot run on its own reservation" later in this series, another rt_mutex_setprio() on the sleeping task evaluates dl_time_before(pi_task->dl.deadline, 0) as false and deboosts it.

Checking dl_se->deadline != 0 before calling dl_hold_refilled_boost() would leave only dl_donor_refill = 1 set so deboost starts a fresh own period.

Quoted 36 lines
kernel/sched/deadline.c +36 -0
+
+static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task);
+static int start_dl_timer(struct sched_dl_entity *dl_se);
+
+/*
+ * End the boost of @dl_se, whose task stays in the class. Then bring the
+ * runtime and the deadline of the task back to its own parameters:
+ *  - After a held boost, dl_end_held_boost() puts back the values that
+ *    dl_hold_refilled_boost() saved. The time the task ran on the
+ *    donor's refills is not charged to its own runtime. If that runtime
+ *    is used up, throttle the task again until its own next period, or
+ *    start that period if it has started.
+ *  - After a refill of a task that had no parameters of its own at the
+ *    refill, start a new period now.
+ *  - Without a refill, the task keeps the runtime and the deadline of its
+ *    own reservation.
+ * Do it now: the next enqueue is too late for a task blocked on another
+ * rt_mutex. The chain walk copies its deadline into its waiter node first.
+ *
+ * The caller holds the rq lock and the pi_lock of the task, and has
+ * updated the rq clock.
+ */
+void dl_deboost(struct sched_dl_entity *dl_se)
+{
+	struct task_struct *p = dl_task_of(dl_se);
+	bool held = dl_end_held_boost(dl_se);
+	bool own = held;
+
+	if (dl_se->dl_donor_refill) {
+		dl_start_own_period(dl_se);
+		own = true;
+	}
+	/*
+	 * If the task blocked while boosted, its inactive timer can be armed
+	 * from the runtime and deadline of the donor's refills. Cancel it, and
+	 * work out the 0-lag time again from the runtime and deadline the task

kernel/sched/deadline.c static inline bool is_dl_boosted(struct sched_dl_entity *dl_se) · line 210

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	 * gets back.
+	 * If the timer handler is already running, it releases the
+	 * bandwidth.
+	 */
+	if (own && dl_se->dl_non_contending &&
+	    hrtimer_try_to_cancel(&dl_se->inactive_timer) == 1) {
+		dl_se->dl_non_contending = 0;
+		put_task_struct(p);
+		task_non_contending(dl_se, true);
+	}

[Severity: Medium]
Can this leave rq->dl.running_bw under-accounted when a task blocks after a donor refill and is deboosted while still blocked?

When a boosted deadline task blocks after a donor refill (with dl_boost_held set), dequeue_dl_entity() calls task_non_contending() -> dl_time_to_zerolag(), which compares the donor's refilled dl_se->runtime against the task's own dl_runtime and dl_period:

kernel/sched/deadline.c:dl_time_to_zerolag() {
    ...
	if (dl_se->runtime > mul_u64_u64_div_u64(left, dl_se->dl_runtime,
						 dl_se->dl_period)) {
		return -1;
	}
    ...
}

If the donor's remaining runtime exceeds what the task's own bandwidth could leave, dl_time_to_zerolag() returns -1 (or an early 0-lag time whose inactive_timer expires before the task's own 0-lag time), so task_non_contending() calls sub_running_bw() immediately and leaves dl_se->dl_non_contending == 0. When dl_deboost() later restores the task's exhausted own_runtime and own_deadline while the task is still blocked, dl_se->dl_non_contending is 0, so the task's dl_bw is not added back to rq->dl.running_bw and inactive_timer is not armed for its true 0-lag time, allowing GRUB tasks on the runqueue to reclaim bandwidth the task already used in its period.

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	dl_drop_boost(dl_se);
+
+	/*
+	 * A held boost can end before the task's own next period, with its
+	 * own runtime used up. Throttle the task until that period. If
+	 * start_dl_timer() finds that the period has already started, start
+	 * it now.
+	 */
+	if (held && dl_se->runtime <= 0) {
+		struct rq *rq = task_rq(p);

kernel/sched/deadline.c static inline bool is_dl_boosted(struct sched_dl_entity *dl_se) · line 230

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+
+		dl_se->dl_throttled = 1;
+		if (!start_dl_timer(dl_se)) {
+			dl_se->dl_throttled = 0;
+			dl_start_own_period(dl_se);
+		} else if (task_current_donor(rq, p)) {
+			resched_curr(rq);
+		}
+	}
+}

[Severity: Medium]
Does dl_deboost() start a new period (or arm dl_timer to replenish one) while a constrained-deadline task is sleeping on a non-PI waitqueue?

If a constrained-deadline task (dl_deadline < dl_period) holding an rt_mutex is deboosted while sleeping (!task_on_rq_queued(p) && !p->pi_blocked_on), dl_end_held_boost() and dl_deboost() either call dl_start_own_period() immediately or arm dl_timer via start_dl_timer(), which replenishes and starts a period in dl_task_timer() while the task remains asleep. Because that period ticks while the task is sleeping, waking up before the deadline causes update_dl_revised_wakeup() to trim its runtime for the time spent asleep, and waking up in the constrained gap between the deadline and the next period causes dl_check_constrained_dl() to throttle the task until the following period even though it never ran.

Commit "sched/deadline: Keep the debt of a task across a change of parameters" later in this series avoids starting a period or arming dl_timer for an asleep constrained-deadline task in dl_setattr_place() so that wakeup either throttles it until next or starts a fresh period on wakeup.

[ ... ]

kernel/sched/deadline.c static void replenish_dl_entity(struct sched_dl_entity *dl_se) · line 1382

Quoted 12 lines
kernel/sched/deadline.c +3 -1
@@ -1231,8 +1373,10 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 			dl_se->deadline = rq_clock(rq);
 			dl_se->runtime = 0;
 		}
-		if (dl_se->runtime < 0 || dl_se->dl_yielded)
+		if (dl_se->runtime < 0 || dl_se->dl_yielded) {
 			dl_se->runtime = 0;
+			dl_note_donor_refill(dl_se);
+		}
 		dl_se->dl_yielded = 0;
 		dl_se->dl_throttled = 0;
 		return;

[Severity: Medium]
When a boosted task with !dl_se->dl_deadline is replenished after its donor's parameters were cleared (!runtime || !deadline || !period), does this miss calling dl_note_donor_refill(dl_se)?

The !dl_se->dl_deadline block sets dl_se->deadline = rq_clock(rq) and dl_se->runtime = 0 without calling dl_note_donor_refill(dl_se), and zeroing dl_se->runtime prevents the following dl_se->runtime < 0 check from calling it either. If sched_setattr() then gives the task SCHED_DEADLINE parameters during the boost, dl_deboost() sees both dl_boost_held == 0 and dl_donor_refill == 0 and leaves the task with runtime == 0 and the stale rq_clock(rq) deadline instead of starting its own period (or a subsequent donor refill sees first == true and saves that artificial deadline and 0 runtime as own_deadline and own_runtime).

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

Re: [PATCH v11 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] sched/deadline: dl_proxy_block() skips overflow check for boosted tasks - [Medium]…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] sched/deadline: dl_proxy_block() skips overflow check for boosted tasks
- [Medium] locking/rtmutex: race in __rt_mutex_start_proxy_lock() after dl_proxy_block()
- [Medium] sched/deadline: dl_note_donor_refill() saves zero own_deadline
- [Medium] sched/deadline: missing dl_proxy_block() in futex_proxy_trylock_atomic()
--

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

sched/deadline: Start a period for a task requeued onto an rt_mutex

This commit adds dl_proxy_block() and calls it from __rt_mutex_start_proxy_lock() so that a sleeping SCHED_DEADLINE task requeued onto an rt_mutex via FUTEX_CMP_REQUEUE_PI has its deadline updated before the trylock and waiter insertion.

Quoted 9 lines
kernel/locking/rtmutex_api.c +1 -0
index 6bdbd36bac949..f1246efc62d3a 100644
@@ -342,6 +342,18 @@ int __sched __rt_mutex_start_proxy_lock(struct rt_mutex_base *lock,
 
 	lockdep_assert_held(&lock->wait_lock);
 
+	/*

kernel/locking/rtmutex_api.c int __sched __rt_mutex_start_proxy_lock(struct rt_mutex_base *lock, · line 355

Quoted 10 lines
kernel/locking/rtmutex_api.c +10 -0
+	 * A requeued @task sleeps, so its deadline can be stale. The trylock
+	 * below and the waiter node both read it: update it first.
+	 * futex_lock_pi() passes current, which is running. Its deadline is
+	 * up to date.
+	 */
+	if (task != current) {
+		raw_spin_lock(&task->pi_lock);
+		dl_proxy_block(task);
+		raw_spin_unlock(&task->pi_lock);
+	}

[Severity: Medium]
Can releasing task->pi_lock here before task->pi_blocked_on is set race with sched_setattr() or PI boosting on another CPU?

If task is not in SCHED_DEADLINE when dl_proxy_block() runs, it returns with task->dl.deadline still at 0. Before task_blocks_on_rt_mutex() re-acquires task->pi_lock and sets task->pi_blocked_on, another CPU can switch or boost task into SCHED_DEADLINE:

CPU0 CPU1
__rt_mutex_start_proxy_lock()
raw_spin_lock(&task->pi_lock)
dl_proxy_block(task)

    !dl_task(task) -> returns
  raw_spin_unlock(&task->pi_lock)
                                      __sched_setscheduler(task, ...)
                                        raw_spin_lock(&task->pi_lock)
                                        switched_to_dl()
                                          !dl_task_pi_blocked(task)
                                          /* task->dl.deadline stays 0 */
                                        raw_spin_unlock(&task->pi_lock)
  try_to_take_rt_mutex() /
  task_blocks_on_rt_mutex()
    raw_spin_lock(&task->pi_lock)
    waiter_update_prio(waiter, task)  <-- copies deadline == 0
    task->pi_blocked_on = waiter
    raw_spin_unlock(&task->pi_lock)

Because task->pi_blocked_on is still NULL when switched_to_dl() runs on CPU1, switched_to_dl() leaves task->dl.deadline at 0. CPU0 then uses deadline 0 to steal the lock or enqueue the waiter ahead of all real deadline waiters.

kernel/locking/rtmutex_api.c int __sched __rt_mutex_start_proxy_lock(struct rt_mutex_base *lock, · line 358

Quoted 3 lines
kernel/locking/rtmutex_api.c +1 -0
+
 	if (try_to_take_rt_mutex(lock, task, NULL))
 		return 1;

[Severity: Medium]
Does the uncontended FUTEX_CMP_REQUEUE_PI fast path in futex_proxy_trylock_atomic() also need to call dl_proxy_block() on the new owner?

When the target PI futex is uncontended and nr_requeue >= 1, futex_requeue() acquires the futex for top_waiter->task via futex_proxy_trylock_atomic() -> futex_lock_pi_atomic(), attaches top_waiter->task as the pi_mutex owner, and wakes it without going through __rt_mutex_start_proxy_lock():

kernel/futex/requeue.c:futex_proxy_trylock_atomic() {
	...
	ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
				   exiting, set_waiters);
	if (ret == 1) {
		requeue_pi_wake_futex(top_waiter, key2, hb2);
	...
}

If try_to_wake_up() queues top_waiter->task on a remote CPU's wake_list via ttwu_queue_wakelist(), enqueue_task_dl() -> update_dl_entity() has not run yet when futex_requeue() loops to requeue the next waiter onto that pi_mutex via rt_mutex_start_proxy_lock(). The boost check against the new owner then sees top_waiter->task's stale deadline (0, expired, or overflowed), which can miss a boost from a waiter or cause the subsequent donor refill at wakeup on the remote CPU to save the unreplenished stale deadline as own_deadline.

Quoted 35 lines
kernel/sched/deadline.c +27 -0
index 5d1d4ea288788..c59953e80b1a9 100644
@@ -1682,6 +1682,59 @@ static inline u64 dl_next_period(struct sched_dl_entity *dl_se)
 	return dl_se->deadline - dl_se->dl_deadline + dl_se->dl_period;
 }
 
+#ifdef CONFIG_RT_MUTEXES
+/*
+ * FUTEX_CMP_REQUEUE_PI makes @p wait on an rt_mutex while @p sleeps.
+ * The waiter node of @p takes its deadline before any wakeup. So apply
+ * the wakeup rule of update_dl_entity() to @p now:
+ * - A deadline of 0, which a task that entered the class asleep has,
+ *   gets a new period.
+ * - A constrained task past its deadline and before its next period
+ *   keeps its deadline. Its wakeup throttles it until that period. Its
+ *   waiter node keeps that passed deadline, and sorts first.
+ * - Any other task gets the check of update_dl_entity(). A deadline
+ *   that has passed gets a new period.
+ *
+ * The caller holds the pi_lock of @p.
+ */
+void dl_proxy_block(struct task_struct *p)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+	struct rq_flags rf;
+	struct rq *rq;
+
+	if (!dl_task(p))
+		return;
+	rq = __task_rq_lock(p, &rf);
+	update_rq_clock(rq);
+	if (task_on_rq_queued(p) || dl_se->dl_throttled)
+		goto unlock;

kernel/sched/deadline.c static inline u64 dl_next_period(struct sched_dl_entity *dl_se) · line 1721

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	/*
+	 * A boosted task runs on the parameters of its donor. Start a period
+	 * from them if its deadline is 0 or has passed. A task in the class
+	 * with no runtime of its own is always boosted: the test of
+	 * dl_runtime is only a guard.
+	 */
+	if (is_dl_boosted(dl_se) || !dl_se->dl_runtime) {
+		if (!dl_se->deadline ||
+		    dl_time_before(dl_se->deadline, rq_clock(rq)))
+			replenish_dl_new_period(dl_se, rq);

[Severity: Medium]
When a boosted sleeping task has dl_se->deadline == 0 and dl_se->dl_runtime > 0, does replenish_dl_new_period() here record own_deadline = 0 via dl_note_donor_refill()?

If a sleeping non-deadline task is first PI-boosted via an rt_mutex it owns and then given its own SCHED_DEADLINE parameters via sched_setattr() while still asleep, dl_se->dl_runtime is non-zero while dl_se->deadline and dl_se->dl_donor_refill are still 0. Calling replenish_dl_new_period() from dl_proxy_block() runs dl_note_donor_refill():

kernel/sched/deadline.c:dl_note_donor_refill() {
	...
	first = !dl_se->dl_donor_refill;
	dl_se->dl_donor_refill = 1;
	if (first && dl_se->dl_runtime && !dl_se->dl_boost_held)
		dl_hold_refilled_boost(dl_se);
}

Because dl_note_donor_refill() checks dl_se->dl_runtime without checking whether dl_se->deadline is non-zero, dl_hold_refilled_boost() saves own_deadline = 0 and sets dl_boost_held = 1. When the boost ends, dl_end_held_boost() can restore dl_se->deadline = 0 and throttle the task with a zero deadline, causing its waiter node to sort ahead of all real deadlines.

Quoted 4 lines
kernel/sched/deadline.c +4 -0
+		goto unlock;
+	}
+	if (!dl_se->deadline) {
+		replenish_dl_new_period(dl_se, rq);

kernel/sched/deadline.c static inline u64 dl_next_period(struct sched_dl_entity *dl_se) · line 1735

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+		goto unlock;
+	}
+	if (!dl_is_implicit(dl_se) &&
+	    dl_time_before(dl_se->deadline, rq_clock(rq)) &&
+	    dl_time_before(rq_clock(rq), dl_next_period(dl_se)))
+		goto unlock;
+	update_dl_entity(dl_se);
+unlock:
+	__task_rq_unlock(rq, p, &rf);
+}

[Severity: Medium]
Should the boosted branch in dl_proxy_block() also check dl_entity_overflow(dl_se, rq_clock(rq)) as update_dl_entity() does?

In update_dl_entity(), a boosted task whose deadline has not yet passed still gets a new donor period when dl_entity_overflow(dl_se, rq_clock(rq)) is true:

kernel/sched/deadline.c:update_dl_entity() {
	if (dl_time_before(dl_se->deadline, rq_clock(rq)) ||
	    dl_entity_overflow(dl_se, rq_clock(rq))) {
		if (unlikely((!dl_is_implicit(dl_se) ||
			      (dl_se->dl_defer && dl_se->dl_defer_running)) &&
			     !dl_time_before(dl_se->deadline, rq_clock(rq)) &&
			     !is_dl_boosted(dl_se))) {
			update_dl_revised_wakeup(dl_se, rq);
			return;
		}

		dl_se->dl_defer_running = 0;
		replenish_dl_new_period(dl_se, rq);
	}
}

Because dl_proxy_block() only tests !dl_se->deadline || dl_time_before(dl_se->deadline, rq_clock(rq)) for boosted tasks and then jumps to unlock, a boosted task requeued after its overflow threshold but before dl_se->deadline keeps its stale earlier deadline for the trylock, waiter sorting, and owner boosting, even though waking it would immediately postpone its deadline to a new donor period.

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

Re: [PATCH v11 42/43] selftests/sched: Test parameter changes in deadline_bw_test

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] selftests/sched: premature bandwidth probe after reenter_runnable_in_gap() - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] selftests/sched: premature bandwidth probe after reenter_runnable_in_gap()
- [Medium] selftests/sched: missing rival readiness wait in owner_boost_case()
--

commit 1245641ca231366ed56f97e5e4afa480f85900ad
Author: Mathieu Desnoyers <[email protected]>

selftests/sched: Test parameter changes in deadline_bw_test

This commit adds 39 test cases to deadline_bw_test covering SCHED_DEADLINE parameter changes, priority inheritance boosting, and tasks re-entering the deadline class during a constrained gap, and waits for total_bw to drain between partition test cases.

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
index 83dd8b4e79a3d..78b58888e9d54 100644

[ ... ]

Quoted 1 line
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
@@ -2749,93 +2923,3168 @@ static int requeue_pi_new_period(void)

[ ... ]

Quoted 65 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +65 -0
+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) {

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

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +10 -0
+		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;

[Severity: Medium]
Can measured() probe cg_p before rr_t's 0-lag time at 500ms and report a false bandwidth leak?

Unlike reenter_pi_blocked_in_gap() and reenter_asleep_case(), which wait for T to run at 500ms before returning, reenter_runnable_in_gap() switches rr_t to SCHED_OTHER and returns at about 90ms while rr_t's 2% bandwidth is still held by its inactive timer until 500ms. Because the case is registered as MEASURED_IN_P, measured() only waits 3 * PERIOD (300ms, reaching about 390ms) before running probe(cg_p):

tools/testing/selftests/sched/deadline/deadline_bw_test.c:measured() {
    ...
	ret = run_in(cg, fn);
	sleep_ns(3 * PERIOD);
	after = probe(cg);
    ...
}

If probe(cg_p) spawns its nine 10% tasks before 500ms, the ninth task fails admission with -EBUSY (5% fair server + 2% rr_t + 90% > 95%) and fails the test.

[ ... ]

Quoted 41 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +41 -0
+/*
+ * Run as the rival C of pi_owner_throttled_rival(). Become a deadline
+ * task of 40ms in 60ms, every 100ms. Wait until W is about to block,
+ * then sleep until 13ms after O's start, and spin 40ms of CPU time.
+ * Return NULL, or 1 on an error.
+ */
+static void *ob_rival(void *arg)
+{
+	struct timespec ts;
+	uint64_t end;
+	int err;
+
+	err = set_constrained(0, 40 * NSEC_PER_MSEC, 60 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the rival refused as a deadline task: %s\n",
+			       strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&ob_rival_go);
+	end = ob_t0 + 13 * 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)
+		;
+	spin_ns(40 * NSEC_PER_MSEC);
+	if (set_other(0))
+		ksft_print_msg("the rival cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run an owner_boost case of @kind: ob_owner() and ob_waiter(), and
+ * ob_rival() with OB_RIVAL. W must get pi_lock within @limit_ms of O's
+ * start.
+ */
+static int owner_boost_case(int kind, int limit_ms)
+{
+	void *o_ret = NULL, *w_ret = NULL, *c_ret = NULL;
+	int throttled = kind != OB_GAP && kind != OB_LATE_GAP;
+	int ret = KSFT_FAIL;
+	pthread_t o, w, c;

[ ... ]

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

Quoted 8 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +8 -0
+	if (kind == OB_GAP)
+		sleep_ns(30 * NSEC_PER_MSEC);	/* O sleeps past its deadline */
+	if (kind == OB_RIVAL && pthread_create(&c, NULL, ob_rival, NULL)) {
+		ksft_print_msg("the rival thread could not start\n");
+		kind = OB_THROTTLED;
+		c_ret = (void *)1;
+	}
+	sem_post(&ob_go);

[Severity: Medium]
Can ob_waiter preempt ob_rival before ob_rival enters SCHED_DEADLINE?

On P's single CPU, owner_boost_case() creates ob_rival and immediately posts ob_go to wake ob_waiter without waiting for ob_rival to finish set_constrained():

  main thread (CPU of P)        ob_waiter             ob_rival
  ----------------------        ---------             --------
  pthread_create(..., ob_rival)
  sem_post(&ob_go)
                                wakes as SCHED_OTHER
                                set_deadline(2ms, 10ms)
                                sem_post(&ob_rival_go)
                                take_pi_lock()
                                  boosts ob_owner
                                  ob_owner spins 5ms
                                  unlocks at 15ms
                                                      first scheduled
                                                      set_constrained(...)

When ob_waiter runs before the newly created ob_rival thread, ob_waiter and the boosted ob_owner keep the single CPU in SCHED_DEADLINE until the lock hand-off is already over at 15ms, so pi_owner_throttled_rival() passes without ob_rival competing at 13ms.

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

Re: [PATCH v11 41/43] sched/deadline: Run a boost held at its first refill on a donor period

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: corrupted donor period state when donor params are cleared - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: corrupted donor period state when donor params are cleared
- [Medium] sched/deadline: stale donor period or zero runtime in dl_boost_donor_period()
--

commit 5fe21dc7cf6ba0759a7b3c870c560c1b847c8ab3
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Run a boost held at its first refill on a donor period

This commit updates dl_hold_refilled_boost() and replenish_dl_new_period() so that a boost held at its first refill from a donor runs on a resumed or newly started donor period via dl_boost_donor_period().

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 52095e24638cc..3d573bf812eed 100644

[ ... ]

Quoted 6 lines
kernel/sched/deadline.c +0 -2
@@ -1663,11 +1668,13 @@ static void wakeup_preempt_dl(struct rq *rq, struct task_struct *p, int flags);
 static inline void replenish_dl_new_period(struct sched_dl_entity *dl_se,
 					    struct rq *rq)
 {
-	dl_note_donor_refill(dl_se);
-	/* for non-boosted task, pi_of(dl_se) == dl_se */

kernel/sched/deadline.c static void wakeup_preempt_dl(struct rq *rq, struct task_struct *p, int flags); · line 1677

Quoted 10 lines
kernel/sched/deadline.c +7 -3
-	dl_se->period_start = rq_clock(rq);
-	dl_se->deadline = dl_se->period_start + pi_of(dl_se)->dl_deadline;
-	dl_se->runtime = pi_of(dl_se)->dl_runtime;
+	/* A boost held from this refill keeps the period it placed. */
+	if (!dl_note_donor_refill(dl_se)) {
+		/* for non-boosted task, pi_of(dl_se) == dl_se */
+		dl_se->period_start = rq_clock(rq);
+		dl_se->deadline = dl_se->period_start + pi_of(dl_se)->dl_deadline;
+		dl_se->runtime = pi_of(dl_se)->dl_runtime;
+	}

[Severity: Medium]
Can keeping the period placed by dl_note_donor_refill() here leave dl_se->runtime at 0 or resume a stale donor's deadline and runtime?

kernel/sched/deadline.c:dl_boost_donor_period() {
	...
	if (dl_se->dl_boost_granted && runtime && period &&
	    dl_time_before(now, dl_se->boost_period_start + period)) {
		dl_se->period_start = dl_se->boost_period_start;
		dl_se->deadline = dl_se->boost_deadline;
		dl_se->runtime = dl_se->boost_runtime;
		if (!dl_time_before(now, dl_se->deadline)) {
			dl_se->period_start += period;
			dl_se->deadline += period;
			dl_se->runtime = runtime;
		}
		if (dl_entity_overflow(dl_se, now))
			dl_se->runtime = (READ_ONCE(pi_se->dl_density) *
					  (dl_se->deadline - now)) >> BW_SHIFT;
		return;
	}
	...
}

When replenish_dl_new_period() is the first refill that holds the boost (for example from update_dl_entity() on wakeup, or at the end of replenish_dl_entity() when the owner still had positive runtime left past its own deadline), there is no while (dl_se->runtime <= 0) loop after it. If dl_boost_donor_period() resumes a granted period where boost_runtime is 0, or where the density calculation near boost_deadline truncates to 0, replenish_dl_new_period() returns with dl_se->runtime == 0.

In addition, if the previous held boost came from a different donor (or the same donor before sched_setattr()) with a longer deadline and larger runtime, dl_boost_donor_period() resumes boost_deadline and boost_runtime as long as now is before boost_period_start + period, without checking that they match the current donor's dl_deadline and dl_runtime. That can give the owner a deadline later than the current waiter's (or its own) and a runtime larger than the current donor's dl_runtime.

[ ... ]

Quoted 22 lines
kernel/sched/deadline.c +7 -3
@@ -6016,11 +6026,15 @@ static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
  * If sched_setattr() changed the parameters before this refill,
  * dl_setattr_period() saved the old ones in setattr_*. Fit the period
  * saved in own_* to the new parameters with them. setattr_* share
- * storage with own_*: read them before writing own_*. The caller holds
- * the rq lock of the task, and has updated the rq clock.
+ * storage with own_*: read them before writing own_*. Return true if a
+ * period of the donor was placed. The caller holds the rq lock of the
+ * task, and has updated the rq clock.
  */
-static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
+static bool dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
 {
+	struct sched_dl_entity *pi_se = pi_of(dl_se);
+	u64 donor_runtime = READ_ONCE(pi_se->dl_runtime);
+	u64 donor_deadline = READ_ONCE(pi_se->dl_deadline);
 	u64 old_runtime = dl_se->setattr_runtime;
 	u64 old_deadline = dl_se->setattr_deadline;
 	u64 old_period = dl_se->setattr_period;
@@ -6037,6 +6051,14 @@ static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
 		dl_setattr_place(dl_se, now, &dl_se->own_period_start,
 				 &dl_se->own_deadline, &dl_se->own_runtime,

kernel/sched/deadline.c static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se) · line 6062

Quoted 10 lines
kernel/sched/deadline.c +8 -0
 				 old_runtime, old_deadline, old_period, false, false);
+	/*
+	 * replenish_dl_entity() checks the donor's parameters: it adds no
+	 * runtime if they were cleared. Start no period from them then.
+	 */
+	if (!donor_runtime || !donor_deadline)
+		return false;
+	dl_boost_donor_period(dl_se);
+	return true;
 }

[Severity: Medium]
When the donor leaves SCHED_DEADLINE and has its parameters cleared on another CPU before the rt_mutex chain walk deboosts the owner, can returning false here after setting dl_se->dl_boost_held = 1 corrupt the owner's period and saved boost state?

First, in replenish_dl_entity(), if the donor's parameters are already cleared at the initial check, dl_note_donor_refill() is called when dl_se->runtime < 0 or dl_se->dl_yielded is set. dl_hold_refilled_boost() sets dl_se->dl_boost_held = 1 and returns false without placing a donor period, leaving dl_se->deadline and dl_se->period_start set to the owner's own period with dl_se->runtime == 0. When the boost ends, dl_end_held_boost() sees dl_boost_held == 1 and saves the owner's own period with boost_runtime = 0 into boost_* and sets dl_boost_granted = 1, so the next held boost from a valid donor resumes the owner's old period with 0 runtime.

Second, when dl_note_donor_refill() is called from replenish_dl_new_period(), returning false from dl_hold_refilled_boost() causes replenish_dl_new_period() to enter the !dl_note_donor_refill(dl_se) branch and overwrite dl_se->period_start = rq_clock(rq), dl_se->deadline = dl_se->period_start + 0, and dl_se->runtime = 0 from the cleared donor parameters anyway.

Third, because dl_hold_refilled_boost() (which also omits checking pi_se->dl_period), dl_boost_donor_period(), and replenish_dl_new_period() re-read pi_se's parameters instead of using replenish_dl_entity()'s validated snapshot, a concurrent __dl_clear_params(pi_se) after replenish_dl_entity()'s initial check makes dl_hold_refilled_boost() return false while replenish_dl_entity() proceeds to the while (dl_se->runtime <=
0) loop, advancing the owner's own deadline by the donor's period.

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

Re: [PATCH v11 37/43] sched/deadline: Keep the debt of a task across a change of parameters

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 8 potential issues to consider: - [Medium] sched/deadline: unthrottled zero-runtime wakeup in dl_setattr_place() - [Medium] sched/deadline…

Thank you for your contribution! Sashiko AI review found 8 potential issues to consider:
- [Medium] sched/deadline: unthrottled zero-runtime wakeup in dl_setattr_place()
- [Medium] sched/deadline: deferred boost debt and timer race in dl_setattr_period()
- [Medium] sched/deadline: missing zero-deadline check in dl_in_constrained_gap()
- [Medium] sched/deadline: redundant update_dl_entity() check after dl_setattr_period()
- [Medium] sched/deadline: mismatched period fitting in dl_drop_boost_out()
- [Medium] sched/deadline: own_runtime zeroed before debt calc in dl_hold_refilled_boost()
- [Medium] sched/deadline: extra period bw retention when dl_task_timer() refills departed task
- [Medium] sched/deadline: stale inactive_timer when sched_setattr() keeps same dl_bw
--

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

sched/deadline: Keep the debt of a task across a change of parameters

This commit fits the period in progress of a SCHED_DEADLINE task to new parameters across sched_setattr() so that any accumulated runtime debt is preserved and repaid at the new bandwidth.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 23186eb9968e8..1ec7789e81b86 100644

[ ... ]

Quoted 6 lines
kernel/sched/deadline.c +2 -0
@@ -130,6 +132,19 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
 	return true;
 }
 
+/*
+ * Return true if @dl_se has a constrained deadline, and the rq clock is

kernel/sched/deadline.c static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se) · line 146

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+ * past its deadline and before its next period. An enqueue then throttles
+ * it until that period.
+ */
+static inline bool dl_in_constrained_gap(struct sched_dl_entity *dl_se)
+{
+	u64 now = rq_clock(rq_of_dl_se(dl_se));
+
+	return !dl_is_implicit(dl_se) && dl_time_before(dl_se->deadline, now) &&
+	       dl_time_before(now, dl_se->period_start + dl_se->dl_period);
+}

[Severity: Medium]
Should dl_in_constrained_gap() check that dl_se->deadline is non-zero first, as dl_proxy_block() does?

For a task new to SCHED_DEADLINE (or after __dl_clear_params()), both deadline and period_start are 0. If the task is blocked on an rt_mutex and given a constrained deadline while rq_clock(rq) < dl_se->dl_period, dl_in_constrained_gap() returns true, so both dl_check_blocked_params() and switched_to_dl() skip starting a period and leave deadline == 0 in the task's rt_mutex waiter node.

[ ... ]

Quoted 1 line
kernel/sched/deadline.c +0 -0
@@ -227,12 +272,80 @@ void dl_deboost(struct sched_dl_entity *dl_se)

[ ... ]

kernel/sched/deadline.c void dl_deboost(struct sched_dl_entity *dl_se) · line 321

Quoted 9 lines
kernel/sched/deadline.c +9 -0
+void dl_drop_boost_out(struct sched_dl_entity *dl_se)
+{
+	bool saved = dl_se->dl_setattr_saved && !dl_se->dl_donor_refill;
+
+	dl_drop_boost(dl_se);
+	if (saved)
+		dl_setattr_period(dl_se, dl_se->setattr_runtime,
+				  dl_se->setattr_deadline, dl_se->setattr_period);
+}

[Severity: Medium]
Does dl_drop_boost_out() fit the period with different rules from the ones switched_from_dl() just used to arm inactive_timer?

When a boosted task with dl_setattr_saved leaves SCHED_DEADLINE, switched_from_dl() runs first and computes the 0-lag time via dl_zerolag_period(), which calls dl_setattr_place() with run = false (so keep = 0). dl_drop_boost_out() then calls dl_setattr_period(), which passes run = !dl_se->dl_throttled && !asleep. For a queued or pi-blocked task with runtime > 0, dl_setattr_place() keeps up to dl_runtime, pushes period_start and deadline past the 0-lag time that inactive_timer was armed for, and leaves runtime = keep unthrottled (or, when keep == 0 and debt > 0, sets dl_throttled = 1 and arms dl_timer on a task that has already left SCHED_DEADLINE).

[ ... ]

kernel/sched/deadline.c static enum hrtimer_restart dl_task_timer(struct hrtimer *timer) · line 2117

Quoted 11 lines
kernel/sched/deadline.c +4 -0
@@ -1934,6 +2108,10 @@ static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
 		if (dl_se->dl_throttled && !is_dl_boosted(dl_se)) {
 			sched_clock_tick();
 			update_rq_clock(rq);
+			/* Not before the next period: see below. */
+			if (dl_time_before(rq_clock(rq), dl_next_period(dl_se)) &&
+			    start_dl_timer(dl_se))
+				goto unlock;
 			replenish_dl_entity(dl_se);
 		}
 		goto unlock;

[Severity: Medium]
When a throttled constrained-deadline task leaves SCHED_DEADLINE, can replenishing it here in dl_task_timer() cause inactive_task_timer() to hold its bandwidth for an extra period?

Both dl_timer and inactive_timer are armed for dl_next_period(dl_se) (or dl_timer fires first when an overrun places the 0-lag time after dl_next_period(dl_se)). When dl_task_timer() runs replenish_dl_entity(), it advances dl_se->period_start by dl_period, so inactive_task_timer() then sees dl_next_period(dl_se) - rq_clock(rq) > 0 and restarts itself for another full period before releasing total_bw:

kernel/sched/deadline.c:inactive_task_timer() {
    ...
	if (!dl_task(p) && READ_ONCE(p->__state) != TASK_DEAD &&
	    !dl_is_implicit(dl_se)) {
		s64 left = dl_next_period(dl_se) - rq_clock(rq);

		if (left > 0) {
			ktime_t at = ktime_add_ns(hrtimer_cb_get_time(timer), left);

			hrtimer_set_expires(timer, at);
			task_rq_unlock(rq, p, &rf);
			return HRTIMER_RESTART;
		}
	}
    ...
}

[ ... ]

Quoted 10 lines
kernel/sched/deadline.c +2 -3
@@ -3159,12 +3361,13 @@ enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags)
 		update_dl_entity(dl_se);
 	} else if (flags & ENQUEUE_REPLENISH) {
 		replenish_dl_entity(dl_se);
-	} else if ((flags & ENQUEUE_CLASS) && !is_dl_boosted(dl_se)) {
+	} else if (((flags & ENQUEUE_CLASS) || new_params) &&
+		   !is_dl_boosted(dl_se)) {
 		/*
-		 * The task enters the class, or its parameters change, while
-		 * it is runnable. It may come back before

kernel/sched/deadline.c enqueue_dl_entity(struct sched_dl_entity *dl_se, int flags) · line 3373

Quoted 10 lines
kernel/sched/deadline.c +4 -3
-		 * its deadline, with the runtime left from older parameters.
-		 * Check that runtime against the new parameters,
-		 * as a wakeup does.
+		 * The task enters the class, or its parameters change, while
+		 * it is runnable. It may have runtime left from older
+		 * parameters. Check that runtime against the new parameters,
+		 * as a wakeup does.
 		 */
 		update_dl_entity(dl_se);
 	} else if ((flags & ENQUEUE_MOVE) &&

[Severity: Medium]
Does testing (flags & ENQUEUE_CLASS) here run update_dl_entity() on a period that dl_setattr_period() has already fitted?

When a runnable task leaves SCHED_DEADLINE and re-enters before its 0-lag time with modified parameters, __setparam_dl() fits the period via dl_setattr_period() and clears dl_new_params. As noted in the comment on dl_setattr_period(), running update_dl_entity() afterward checks dl_entity_overflow() at microsecond granularity, which can see a rounding overflow on the just-fitted period and call replenish_dl_new_period(), wiping out the debt. In __setparam_dl(), the !pending guard has the same effect when dl_new_params was already set before a change that dl_setattr_period() fits.

[ ... ]

Quoted 1 line
kernel/sched/deadline.c +0 -0
@@ -5325,47 +5529,298 @@ int sched_dl_overflow(struct task_struct *p, int policy,

[ ... ]

Quoted 5 lines
kernel/sched/deadline.c +5 -0
+static bool dl_setattr_place(struct sched_dl_entity *dl_se, u64 now,
+			     u64 *start, u64 *deadline, s64 *runtime,
+			     u64 old_runtime, u64 old_deadline, u64 old_period,
+			     bool run, bool asleep)
+{

[ ... ]

kernel/sched/deadline.c int sched_dl_overflow(struct task_struct *p, int policy, · line 5665

Quoted 8 lines
kernel/sched/deadline.c +8 -0
+	*runtime = 0;
+	if (asleep && dl_deadline < dl_period) {
+		if (dl_time_before(next, now))
+			next = now;
+		*start = next - dl_period;
+		*deadline = *start + dl_deadline;
+		return false;
+	}

[Severity: Medium]
What happens if a sleeping task with a new constrained deadline wakes up before *deadline?

When next - now >= dl_period - dl_deadline (for instance, when debt repayment exceeds the constrained gap, or when now < release + dl_deadline forces next >= release + dl_period), *deadline = next - dl_period + dl_deadline is in the future while *runtime is set to 0 and dl_setattr_place() returns false (clearing dl_throttled). If the task wakes up before *deadline, dl_check_constrained_dl() does not throttle it because deadline >= now, and dl_entity_overflow() returns false because left = (dl_deadline >> DL_SCALE) * (0 >> DL_SCALE) = 0 is not greater than right >= 0. The task is then enqueued unthrottled with runtime == 0 before its next period at next.

Quoted 11 lines
kernel/sched/deadline.c +11 -0
+	if (!dl_time_before(now, next)) {
+		*start = now;
+		*deadline = now + dl_deadline;
+		*runtime = dl_runtime;
+		return false;
+	}
+	*start = next - dl_period;
+	*deadline = *start + dl_deadline;
+	return true;
+}
+

[ ... ]

Quoted 3 lines
kernel/sched/deadline.c +3 -0
+static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
+			      u64 old_deadline, u64 old_period)
+{

[ ... ]

kernel/sched/deadline.c int sched_dl_overflow(struct task_struct *p, int policy, · line 5732

Quoted 9 lines
kernel/sched/deadline.c +9 -0
+	if (is_dl_boosted(dl_se)) {
+		if (!dl_se->dl_setattr_saved && !dl_se->dl_donor_refill) {
+			dl_se->setattr_runtime = old_runtime;
+			dl_se->setattr_deadline = old_deadline;
+			dl_se->setattr_period = old_period;
+			dl_se->dl_setattr_saved = 1;
+		}
+		return true;
+	}

[Severity: Medium]
When a boosted task's bandwidth is reduced before any donor refill, does deferring the fit until deboost or refill repay the debt at the old bandwidth instead of the new one?

sched_dl_overflow() immediately releases the old bandwidth in total_bw at sched_setattr(), but dl_setattr_place() is only called later at the deboost or first donor refill with that later timestamp as now. Computing debt = (zerolag - now) * old_runtime / old_period at the later timestamp credits the entire interval since sched_setattr() at old_runtime / old_period rather than the new bandwidth. Also, because setattr_* are only recorded when !dl_setattr_saved, a second sched_setattr() back to the original parameters before deboost leaves dl_setattr_saved set and still fits against the first period's state.

kernel/sched/deadline.c int sched_dl_overflow(struct task_struct *p, int policy, · line 5740

Quoted 8 lines
kernel/sched/deadline.c +8 -0
+
+	/*
+	 * start_dl_timer() does not move a queued timer: cancel it first. If
+	 * its handler is already running, the cancel fails. The handler then
+	 * waits for the rq lock. It finds the task no longer throttled, or
+	 * arms the timer again at the next period set here.
+	 */
+	cancel_replenish_timer(dl_se);

[Severity: Medium]
If a sleeping task has dl_non_contending set and sched_setattr() changes its period without changing dl_bw, can the old inactive_timer fire too early if the task then leaves SCHED_DEADLINE?

When new_bw == dl_se->dl_bw (for example, when changing a constrained dl_deadline to implicit while keeping dl_runtime and dl_period, or scaling both proportionally), dl_change_utilization() returns early and leaves inactive_timer armed for the old 0-lag time. dl_setattr_period() then updates period_start, deadline and runtime, and if the sleeping task subsequently leaves SCHED_DEADLINE, switched_from_dl() sees p->dl.dl_non_contending == 1 and skips task_non_contending(), so inactive_task_timer() fires at the stale pre-setattr 0-lag time and releases the bandwidth and clears the parameters early.

[ ... ]

Quoted 9 lines
kernel/sched/deadline.c +9 -0
+static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
+{
+	u64 old_runtime = dl_se->setattr_runtime;
+	u64 old_deadline = dl_se->setattr_deadline;
+	u64 old_period = dl_se->setattr_period;
+	bool saved = dl_se->dl_setattr_saved;
+	u64 now = rq_clock(rq_of_dl_se(dl_se));
+
+	dl_se->own_deadline = dl_se->deadline;

kernel/sched/deadline.c

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	dl_se->own_runtime = dl_time_before(now, dl_se->deadline) ?
+			     max_t(s64, dl_se->runtime, 0) : 0;
+	dl_se->own_period_start = dl_se->period_start;
+	dl_se->dl_boost_held = 1;
+	dl_se->dl_setattr_saved = 0;
+	if (saved && dl_se->own_deadline && old_runtime && old_period)
+		dl_setattr_place(dl_se, now, &dl_se->own_period_start,
+				 &dl_se->own_deadline, &dl_se->own_runtime,
+				 old_runtime, old_deadline, old_period, false, false);
+}

[Severity: Medium]
Does zeroing or clamping dl_se->own_runtime before calling dl_setattr_place() corrupt the debt calculation?

dl_setattr_place() uses the incoming *runtime to compute how much of the old period's runtime was used (adjusting zerolag by *runtime * old_period / old_runtime) before setting *runtime = 0 when run is false. When a boosted constrained task has unused runtime (dl_se->runtime > 0) and its first donor refill happens after dl_se->deadline (or when sched_setattr() is called later while dl_boost_held is set), zeroing own_runtime first makes dl_setattr_place() treat the entire old_runtime as consumed and charge debt for runtime the task never used.

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

Re: [PATCH v11 38/43] sched/deadline: Boost an owner that cannot run on its own reservation

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 10 potential issues to consider: - [High] sched/deadline: self-donor cycle after policy change skips enqueue_dl_entity() - [Medium]…

Thank you for your contribution! Sashiko AI review found 10 potential issues to consider:
- [High] sched/deadline: self-donor cycle after policy change skips enqueue_dl_entity()
- [Medium] sched/deadline: mismatched donor parameters in dl_boost_donor_period()
- [Medium] sched/deadline: missed deadline update on donor change in rt_mutex_setprio()
- [Medium] sched/deadline: inconsistent throttle state after dl_end_held_boost()
- [Medium] sched/deadline: stale or expired deadline propagated on rt_mutex PI chains
- [Medium] sched/deadline: stale past deadline kept when boosting unqueued owner
- [Medium] sched/deadline: dl_waiter_boosts() ignores positive own_runtime on held boost
- [Medium] sched/deadline: deboost of sleeping constrained task wastes period and runtime
- [Medium] sched/deadline: dl_end_held_boost() zeroes negative own_runtime overrun debt
- [Medium] sched/deadline: rt_mutex_setprio() skips dl_boost_start() for departed task
--

commit 32b5d84720d53a30b294628db937bed83d5c70cf
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Boost an owner that cannot run on its own reservation

This commit updates SCHED_DEADLINE priority inheritance so that a lock owner that is throttled or in its constrained deadline gap is boosted and runs on a donor period, while preserving and resuming the donor period across repeated boosts.

Quoted 33 lines
kernel/sched/core.c +8 -8
index fa032d6dc873a..c1e043d27b67c 100644
@@ -7961,9 +7961,9 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 		 * 1. -rt task is running and holds mutex A
 		 *      --> -dl task blocks on mutex A
 		 *
-		 * 2. -dl task is running and holds mutex A
-		 *      --> -dl task blocks on mutex A and could preempt the
-		 *          running task
+		 * 2. -dl task holds mutex A
+		 *      --> -dl task blocks on mutex A, and dl_waiter_boosts()
+		 *          returns true for it
 		 */
 		if (dl_prio(prio)) {
 			/*
@@ -7975,13 +7975,27 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 			if (!dl_prio(p->normal_prio) ||
 			    (pi_task && dl_prio(pi_task->prio) &&
 			     !(p->dl.dl_new_params && p->dl.pi_se != &p->dl) &&
-			     dl_entity_preempt(&pi_task->dl, &p->dl))) {
+			     dl_waiter_boosts(p, pi_task))) {
 				struct sched_dl_entity *old_donor = p->dl.pi_se;
 
-				dl_set_donor(&p->dl, pi_task);
-				scope->flags |= ENQUEUE_REPLENISH;
-				if (!scope->queued && p->dl.pi_se != old_donor)
-					dl_boost_blocked(p);
+				if (!dl_set_donor(&p->dl, pi_task)) {
+					/*
+					 * The donor of the top waiter is @p: @p waits
+					 * on a lock that it owns. End the boost of a

kernel/sched/core.c void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) · line 7994

Quoted 10 lines
kernel/sched/core.c +10 -0
+					 * deadline task, as a deboost does. Another
+					 * task keeps its donor: a deboost would leave
+					 * it in the class with no parameters.
+					 */
+					if (dl_prio(p->normal_prio) && old_donor != &p->dl)
+						dl_deboost(&p->dl);
+				} else {
+					if (dl_prio(p->normal_prio) &&
+					    old_donor == &p->dl && p->dl.pi_se != &p->dl)
+						dl_boost_start(&p->dl);

[Severity: Medium]
Does gating dl_boost_start(&p->dl) on dl_prio(p->normal_prio) skip holding the boost for a departed deadline task that still carries its own parameters until its 0-lag time?

When a SCHED_DEADLINE task leaves the class while throttled or in its constrained gap, it keeps its non-zero p->dl.dl_runtime and p->dl.dl_throttled state until inactive_timer fires. If a deadline waiter boosts it back into dl_sched_class while !dl_prio(p->normal_prio), dl_boost_start() is skipped here. Although commit "sched/deadline: Run a boost held at its first refill on a donor period" later in this series routes runnable refills through dl_hold_refilled_boost(), an unqueued throttled departed task is still not replenished by dl_boost_blocked() or switched_to_dl(); if it is blocked on another rt_mutex it propagates its stale deadline along the PI chain, and if it wakes up while boosted before p->dl.deadline, enqueue_task_dl() clears dl_throttled and update_dl_entity() enqueues it with runtime <= 0. Since dl_boost_start() already checks !dl_se->dl_runtime, the dl_prio(p->normal_prio) check here can be dropped.

kernel/sched/core.c void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) · line 7995

Quoted 1 line
kernel/sched/core.c +1 -0
+					scope->flags |= ENQUEUE_REPLENISH;

[Severity: Medium]
When p is already in a held boost (old_donor != &p->dl) and a new top waiter with an earlier deadline replaces old_donor, does skipping dl_boost_start() leave p running on the previous donor's later deadline?

Because p->dl.dl_deadline is non-zero and p still has positive donor runtime and a future deadline from old_donor, neither replenish_dl_entity() (via ENQUEUE_REPLENISH) nor dl_boost_blocked() updates p->dl.deadline or p->dl.runtime to the new donor's reservation. If an intermediate-deadline task preempts p, p cannot consume the remaining runtime from old_donor to trigger a refill, causing priority inversion for the urgent new waiter.

kernel/sched/core.c void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) · line 7998

Quoted 3 lines
kernel/sched/core.c +3 -0
+					if (!scope->queued && p->dl.pi_se != old_donor)
+						dl_boost_blocked(p);
+				}

[Severity: Medium]
When a deadline owner p (with p->dl.dl_deadline != 0) is blocked on another rt_mutex (!scope->queued), can the PI chain walk propagate a stale or expired p->dl.deadline to the next lock?

Because scope->queued is false, sched_change_end() does not run enqueue_task_dl(), and dl_boost_blocked() returns early whenever dl_se->dl_deadline != 0. If p is boosted while not throttled and not in its constrained gap, dl_boost_start() also returns early, so waiter_update_prio() and dl_waiter_boosts() on the outer lock use p's own deadline instead of the donor's. Conversely, if p is deboosted while in its constrained gap and blocked on an outer lock, dl_end_held_boost() and dl_deboost() restore p->dl.deadline to own_deadline in the past and set dl_throttled = 1, causing the chain walk to queue p on the outer lock with an expired deadline that spuriously boosts the outer lock's owner.

[ ... ]

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 1ec7789e81b86..a526497c099c3 100644

[ ... ]

Quoted 4 lines
kernel/sched/deadline.c +0 -0
@@ -126,7 +134,15 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
 					       (dl_se->dl_density *
 						(dl_se->deadline - now)) >> BW_SHIFT);
 	} else {

kernel/sched/deadline.c static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se) · line 146

Quoted 10 lines
kernel/sched/deadline.c +8 -0
+		/*
+		 * A new period lifts the throttle. A task asleep since
+		 * before the boost still has its replenishment timer armed
+		 * for its old next period: cancel it.
+		 */
 		dl_start_own_period(dl_se);
+		dl_se->dl_throttled = 0;
+		if (hrtimer_try_to_cancel(&dl_se->dl_timer) == 1)
+			put_task_struct(dl_task_of(dl_se));
 	}

[Severity: Medium]
If a constrained-deadline task goes to sleep holding a lock with remaining runtime > 0 and is boosted and deboosted while asleep during or after its constrained gap, does deboosting it waste its remaining runtime and start a new period while it is still asleep?

When the boost ends before own_period_start + dl_period, dl_end_held_boost() zeroes dl_se->runtime (recording false runtime consumption for 0-lag and sched_setattr() debt calculations) and dl_deboost() throttles the sleeping task and arms dl_timer, which fires and starts a new period while the task sleeps. When the boost ends at or after own_period_start + dl_period, dl_end_held_boost() calls dl_start_own_period() immediately while the task is asleep. In both cases, if the task wakes up after the constrained deadline of that new period, dl_check_constrained_dl() throttles it on wakeup even though it slept through the entire period.

[ ... ]

kernel/sched/deadline.c void dl_deboost(struct sched_dl_entity *dl_se) · line 294

Quoted 13 lines
kernel/sched/deadline.c +7 -0
@@ -264,6 +283,13 @@ void dl_deboost(struct sched_dl_entity *dl_se)
 	if (held && dl_se->runtime <= 0) {
 		struct rq *rq = task_rq(p);
 
+		/*
+		 * The timer can still be armed. enqueue_task_dl() cancels it
+		 * when it boosts a runnable task, but a task that slept through
+		 * the boost kept it. sched_setattr() can have moved the task's
+		 * next period since. Cancel the timer before arming it again.
+		 */
+		cancel_replenish_timer(dl_se);
 		dl_se->dl_throttled = 1;
 		if (!start_dl_timer(dl_se)) {

[Severity: Medium]
Can dl_se->dl_throttled and dl_se->dl_timer be left out of sync with the runtime restored by dl_end_held_boost()?

There are two cases where the throttle state does not match the restored period:
1. switched_from_dl() calls dl_end_held_boost(&p->dl) when a task leaves SCHED_DEADLINE during a held boost, but lacks this re-throttling block; if the task was runnable during the boost, enqueue_task_dl() cleared dl_throttled and canceled dl_timer, leaving p with runtime <= 0 and dl_throttled == 0 (so returning to SCHED_DEADLINE with identical parameters before own_deadline enqueues p with runtime <= 0 or wraps negative runtime into an early period).
2. If a task was throttled while asleep (dl_throttled == 1, dl_timer armed), boosted while asleep, and sched_setattr() started a new period in own_* with own_runtime > 0 via dl_setattr_place() when debt == 0, dl_end_held_boost() takes the now < own_period_start + dl_period branch and restores runtime > 0 without clearing dl_throttled or canceling dl_timer, leaving the deboosted task throttled with positive runtime.

Quoted 22 lines
kernel/sched/deadline.c +18 -0
@@ -347,6 +373,114 @@ void dl_check_blocked_params(struct task_struct *p)
 		update_dl_entity(dl_se);
 	}
 }
+
+/*
+ * Return true if the deadline waiter @pi_task must boost the owner @p,
+ * which has a deadline policy of its own. Compare @pi_task with the
+ * deadline that @p would run on:
+ * - The boost of @p is held: keep it until the next period of @p
+ *   starts. After that, compare with now + dl_deadline.
+ * - @p is not boosted, and cannot run on its own reservation. It is
+ *   throttled, or past its deadline and before its next period. Boost it.
+ * - @p is not boosted, and past its deadline otherwise: its next enqueue
+ *   starts a new period. Compare with now + dl_deadline.
+ * - Else, compare with the deadline of @p.
+ * A special entity (a sugov kthread) always boosts @p.
+ *
+ * The caller holds the rq lock of @p and has updated the rq clock.
+ */
+bool dl_waiter_boosts(struct task_struct *p, struct task_struct *pi_task)
+{

kernel/sched/deadline.c void dl_check_blocked_params(struct task_struct *p) · line 403

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	struct sched_dl_entity *dl_se = &p->dl;
+	u64 now = rq_clock(task_rq(p));
+
+	if (dl_entity_is_special(&pi_task->dl))
+		return true;
+	if (dl_se->dl_boost_held) {
+		if (dl_time_before(now, dl_se->own_period_start + dl_se->dl_period))
+			return true;
+		return dl_time_before(pi_task->dl.deadline, now + dl_se->dl_deadline);
+	}

[Severity: Medium]
Does dl_waiter_boosts() keep a held boost when p has positive own_runtime and an own_deadline earlier than pi_task->dl.deadline?

dl_hold_refilled_boost() also sets dl_boost_held = 1 on a wakeup refill when the donor's density cannot accommodate p's remaining runtime, saving own_runtime > 0 with now < own_deadline. If that early waiter leaves while a waiter with a deadline later than own_deadline remains, returning true here keeps p boosted on the later waiter's deadline instead of deboosting p back to its own earlier deadline and remaining runtime.

kernel/sched/deadline.c void dl_check_blocked_params(struct task_struct *p) · line 412

Quoted 9 lines
kernel/sched/deadline.c +9 -0
+	if (!is_dl_boosted(dl_se)) {
+		if (dl_se->dl_throttled || dl_in_constrained_gap(dl_se))
+			return true;
+		if (dl_time_before(dl_se->deadline, now))
+			return dl_time_before(pi_task->dl.deadline,
+					      now + dl_se->dl_deadline);
+	}
+	return dl_entity_preempt(&pi_task->dl, dl_se);
+}

[Severity: Medium]
When dl_waiter_boosts() boosts an unqueued owner whose deadline is in the past (dl_time_before(dl_se->deadline, now)) and that is neither throttled nor in its constrained gap, what updates p->dl.deadline?

Because p is not queued, sched_change_end() does not run enqueue_task_dl(); dl_boost_start() returns early because p is neither throttled nor in its constrained gap; and dl_boost_blocked() returns early because p->dl.dl_deadline is non-zero. As a result, p becomes boosted with dl_boost_held == 0 while p->dl.deadline remains in the past, so subsequent dl_waiter_boosts() calls on p and waiter_update_prio() in an rt_mutex chain walk compare against p's stale past deadline.

Quoted 34 lines
kernel/sched/deadline.c +34 -0
+
+static bool dl_entity_overflow(struct sched_dl_entity *dl_se, u64 t);
+
+/*
+ * Run @dl_se, whose boost is held, on a period of its donor. Resume the
+ * donor period that the last held boost ran on, unless a whole period of
+ * the current donor has passed since it started. A new period at each
+ * boost would give the task one donor runtime per boost. Nothing charges
+ * the donor for that runtime.
+ *
+ * If the deadline of the resumed period has passed, move to its next
+ * period here, with a full donor runtime. A later enqueue would
+ * otherwise start a period from now, which gives a second donor runtime
+ * too early. As in a refill by replenish_dl_entity(), the task can use
+ * that runtime at once, although its period starts in the future.
+ *
+ * Cap the runtime to the donor's density until the deadline, as
+ * update_dl_revised_wakeup() does at the wakeup of a constrained task.
+ */
+static void dl_boost_donor_period(struct sched_dl_entity *dl_se)
+{
+	struct sched_dl_entity *pi_se = pi_of(dl_se);
+	struct rq *rq = rq_of_dl_se(dl_se);
+	u64 runtime = READ_ONCE(pi_se->dl_runtime);
+	u64 period = READ_ONCE(pi_se->dl_period);
+	u64 now = rq_clock(rq);
+
+	if (dl_se->dl_boost_granted && runtime && period &&
+	    dl_time_before(now, dl_se->boost_period_start + period)) {
+		dl_se->period_start = dl_se->boost_period_start;
+		dl_se->deadline = dl_se->boost_deadline;
+		dl_se->runtime = dl_se->boost_runtime;
+		if (!dl_time_before(now, dl_se->deadline)) {
+			dl_se->period_start += period;

kernel/sched/deadline.c void dl_check_blocked_params(struct task_struct *p) · line 456

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+			dl_se->deadline += period;
+			dl_se->runtime = runtime;
+		}
+		if (dl_entity_overflow(dl_se, now))
+			dl_se->runtime = (READ_ONCE(pi_se->dl_density) *
+					  (dl_se->deadline - now)) >> BW_SHIFT;
+		return;
+	}
+	replenish_dl_new_period(dl_se, rq);
+}

[Severity: Medium]
Can dl_boost_donor_period() resume boost_deadline and boost_runtime from a different donor with incompatible parameters?

dl_end_held_boost() saves boost_deadline, boost_runtime, and boost_period_start without recording which donor or relative deadline produced them. If a previous held boost ran under a donor with a long relative deadline and large runtime and deboosted, and a more urgent donor with a shorter dl_deadline and smaller dl_runtime boosts the same owner before boost_period_start + pi_se->dl_period, dl_boost_donor_period() gives the owner the old donor's far-future boost_deadline (causing priority inversion for the urgent waiter) and caps runtime to (pi_se->dl_density * (boost_deadline - now)) >> BW_SHIFT without capping to pi_se->dl_runtime, which can grant several multiples of the new donor's dl_runtime. Conversely, if the previous boost had a much shorter boost_deadline that has already passed, advancing dl_se->deadline by boost_deadline + period instead of dl_se->period_start + pi_se->dl_deadline sets the new deadline too early and causes dl_entity_overflow() to truncate the new period's runtime.

Quoted 17 lines
kernel/sched/deadline.c +17 -0
+
+/*
+ * Call this when @dl_se gets its first donor, after dl_set_donor(). If
+ * @dl_se cannot run on its own reservation, hold the boost from now. Save
+ * its deadline, runtime and period start in own_*, and set dl_boost_held.
+ * Then run it on a period of the donor. A refill would instead add donor
+ * periods to its own deadline. That is often later than the waiter's.
+ *
+ * A task with no parameters of its own has nothing to save. The caller
+ * holds the rq lock and has updated the rq clock.
+ */
+void dl_boost_start(struct sched_dl_entity *dl_se)
+{
+	if (!dl_se->dl_runtime ||
+	    (!dl_se->dl_throttled && !dl_in_constrained_gap(dl_se)))
+		return;
+	/*

kernel/sched/deadline.c void dl_check_blocked_params(struct task_struct *p) · line 483

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	 * A yield gave up the rest of the task's own period: save no runtime
+	 * for it. The yield does not apply to the donor period placed below.
+	 */
+	dl_se->own_deadline = dl_se->deadline;
+	dl_se->own_runtime = dl_se->dl_yielded ? 0 : dl_se->runtime;
+	dl_se->own_period_start = dl_se->period_start;
+	dl_se->dl_boost_held = 1;
+	dl_se->dl_yielded = 0;
+	dl_boost_donor_period(dl_se);
+}

[Severity: Medium]
When dl_boost_start() saves a negative dl_se->runtime from a throttled task that overran its budget, does dl_end_held_boost() erase that overrun debt if the boost ends after own_deadline?

In dl_end_held_boost(), when now < own_period_start + dl_period and !dl_time_before(now, dl_se->deadline) (for example, during the constrained gap of a constrained-deadline task), dl_se->runtime is unconditionally set to 0 instead of only clamping positive runtime, forgiving the negative overrun saved in own_runtime.

[ ... ]

Quoted 5 lines
kernel/sched/syscalls.c +0 -0
index 4f26601f0530a..165f407f45b34 100644

kernel/sched/syscalls.c static inline void __setscheduler_dl_pi(int newprio, int policy, · line 320

Quoted 9 lines
kernel/sched/syscalls.c +1 -3
@@ -315,10 +315,8 @@ static inline void __setscheduler_dl_pi(int newprio, int policy,
 	if (dl_prio(newprio) && !dl_policy(policy)) {
 		struct task_struct *pi_task = rt_mutex_get_top_task(p);
 
-		if (pi_task) {
-			dl_set_donor(&p->dl, pi_task);
+		if (pi_task && dl_set_donor(&p->dl, pi_task))
 			scope->flags |= ENQUEUE_REPLENISH;
-		}
 	}

[Severity: High]
What happens if a SCHED_DEADLINE task p is the root donor in an rt_mutex lock cycle (so its top waiter pi_task has pi_task->dl.pi_se == &p->dl) and p changes its policy to a non-deadline policy?

Because pi_task->prio is deadline priority, rt_effective_prio() keeps p in dl_sched_class while __setscheduler_params() sets !dl_prio(p->normal_prio). dl_set_donor(&p->dl, pi_task) then sees pi_se == &p->dl and returns false, leaving p->dl.pi_se == &p->dl (!is_dl_boosted(&p->dl)) and omitting ENQUEUE_REPLENISH (the same happens in rt_mutex_setprio() if a waiter still carrying pi_se == &p->dl blocks on p after p left SCHED_DEADLINE). When sched_change_end() or a later wakeup calls enqueue_task_dl(), it hits the !is_dl_boosted(dl_se) && !dl_prio(p->normal_prio) early return without calling enqueue_dl_entity(), leaving p marked TASK_ON_RQ_QUEUED with rq->nr_running incremented while absent from rq->dl.root.

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