Skip to contentSkip to conversation

sched/deadline: bandwidth accounting fixes and selftests

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

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

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

In reply to Mathieu Desnoyers

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

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

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

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

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

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

In reply to Mathieu Desnoyers

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

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

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

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

110 lines not on this page · raw message

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

130 lines not on this page · raw message

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

106 lines not on this page · raw message

Signature · 1 line
2.47.3
#8 lore raw

Re: [PATCH v14 02/39] sched/deadline: Replenish a throttled task boosted while asleep

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] sched/deadline: Fixes trailer cites feff2e65efd8 instead of aee38ea95419 --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] sched/deadline: Fixes trailer cites feff2e65efd8 instead of aee38ea95419
--

commit 43888afc681de375614e3f79133646abba848ae0
Author: Mathieu Desnoyers <[email protected]>

Quoted 56 lines

sched/deadline: Replenish a throttled task boosted while asleep

A deadline task can be throttled as it blocks, with an rt_mutex held. Its replenishment timer is then armed. A deadline waiter can boost the task while it sleeps.

Commit feff2e65efd8 ("sched/deadline: Unthrottle PI boosted threads while enqueuing") lets a boost override the throttle. enqueue_task_dl() lifts the throttle of a boosted task, and dl_task_timer() ignores a boosted task. This covers a task that is enqueued while boosted. But a boost of a sleeping task does not enqueue it.

T is a SCHED_DEADLINE task that holds the rt_mutex L. W is a SCHED_DEADLINE task with an earlier deadline:

T W T's timer

uses up its runtime, sleeps
dl_throttled = 1
start_dl_timer()
pthread_mutex_timedlock(L)
rt_mutex_setprio(T, W)
T sleeps: no enqueue
dl_task_timer()
T is boosted: returns
times out
rt_mutex_setprio(T, NULL)
wakes up
enqueue_dl_entity()
dl_throttled: waits for the timer

The timer has already fired. T would never run again, not even to die of SIGKILL. Every later waiter on L would hang too. This was found by reading.

Fix this by returning early in dl_task_timer() only for a boosted task that is queued. A boosted task that sleeps then takes the existing path for a throttled task that is not queued: it is replenished.

The timer refills the task from the parameters of its donor. After the deboost, the task keeps the runtime and the deadline of that refill. Its wakeup then checks them against its own parameters, as any wakeup does. On v7.4-rc2, a queued boosted task also keeps the values of its donor after the deboost. The priority inheritance series gives the task its own values back.

The refill relies on two earlier patches:
- "sched/deadline: Hold a reference on the deadline donor of a boosted task" is earlier in this series. It keeps the donor from being freed while the task points to it. A chain walk that has not reached the task yet leaves it on an old donor. The refill then uses the parameters of that old donor, as for a queued boosted task.
- "sched/deadline: Do not replenish a boost from cleared parameters" is in the first series. It keeps the refill from looping on the parameters of a donor that left the class.

Quoted 6 lines

The Sashiko AI review of this series found this.

Fixes feff2e65efd8 ("sched/deadline: Unthrottle PI boosted threads while enqueuing")

[Severity: Low]
Should the Fixes tag cite aee38ea95419 ("sched/deadline: Fix races between rt_mutex_setprio() and dl_task_timer()") instead of feff2e65efd8 ("sched/deadline: Unthrottle PI boosted threads while enqueuing")?

That commit only changed enqueue_task_dl() and did not touch dl_task_timer(). The unconditional boosted early return in dl_task_timer() was already present from the earlier commit, so this hang existed before the enqueue_task_dl() change.

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

Re: [PATCH v14 01/39] sched/deadline: Hold a reference on the deadline donor of a boosted task

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: recursive rq lock via put_task_struct() in dl_replace_donor() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: recursive rq lock via put_task_struct() in dl_replace_donor()
--

commit 74640640e887acf19101fa00448dad6b61bef633
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Hold a reference on the deadline donor of a boosted task

This commit holds a task_struct reference on the deadline donor stored in dl.pi_se for boosted tasks, updating it via dl_set_donor() and dl_clear_donor() so an exited donor is not freed while still referenced.

Quoted 13 lines
kernel/sched/sched.h +5 -0
index 20ad13f388cb2..4a73661b62b13 100644
@@ -356,6 +356,82 @@ extern int  sched_dl_global_validate(void);
 extern void sched_dl_do_global(void);
 extern int  sched_dl_overflow(struct task_struct *p, int policy, const struct sched_attr *attr);
 extern void __setparam_dl(struct task_struct *p, const struct sched_attr *attr);
+#ifdef CONFIG_RT_MUTEXES
+/*
+ * Make @pi_se the deadline donor of @dl_se. The caller holds a reference
+ * on the task of @pi_se, unless @pi_se is @dl_se. Put the reference on
+ * the old donor.

kernel/sched/sched.h extern int sched_dl_global_validate(void); · line 373

Quoted 10 lines
kernel/sched/sched.h +10 -0
+ */
+static inline void dl_replace_donor(struct sched_dl_entity *dl_se,
+				    struct sched_dl_entity *pi_se)
+{
+	struct sched_dl_entity *old = dl_se->pi_se;
+
+	WRITE_ONCE(dl_se->pi_se, pi_se);
+	if (old != dl_se)
+		put_task_struct(container_of(old, struct task_struct, dl));
+}

[Severity: Medium]
Can calling put_task_struct() here recursively acquire rq->__lock?

dl_replace_donor() runs with rq->__lock held and lockdep-pinned. On a CONFIG_TINY_RCU=y kernel with CONFIG_RCU_DEFER=n (or older stable kernels without CONFIG_RCU_DEFER), a SysRq-N interrupt arriving while CPU 0 is idle can drop the last reference on an already-exited donor via:

sysrq_handle_unrt() -> normalize_rt_tasks() -> __sched_setscheduler()

    -> __setscheduler_dl_pi() -> dl_clear_donor() -> dl_replace_donor()
    -> put_task_struct() -> call_rcu() -> rcu_resched_if_idle()
    -> resched_cpu(0) -> raw_spin_rq_lock_irqsave()

That recursively acquires and prematurely unlocks cpu_rq(0)->__lock while __sched_setscheduler() still holds and pins it, triggering lockdep recursive-locking and pinned-lock warnings or CONFIG_DEBUG_SPINLOCK recursion bugs.

Returning the old donor task_struct from dl_replace_donor(), dl_set_donor(), and dl_clear_donor() and calling put_task_struct() after releasing rq->__lock (as dl_task_timer() does) would avoid invoking call_rcu() under the runqueue lock.

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

Re: [PATCH v14 08/39] sched/deadline: Keep the deadline of a departed constrained task

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 6 potential issues to consider: - [High] sched/deadline: switched_from_dl() wipes preserved deadline of queued task - [Medium]…

Thank you for your contribution! Sashiko AI review found 6 potential issues to consider:
- [High] sched/deadline: switched_from_dl() wipes preserved deadline of queued task
- [Medium] sched/deadline: non-idempotent dl_release_params() wipes preserved deadline
- [Medium] sched/deadline: preserved deadline breaks PI boost in update_dl_entity()
- [Medium] sched/deadline: dl_release_params() retains stale deadline across reentry
- [Medium] sched/deadline: dl_release_params() leaves future deadline with zero runtime
- [Medium] sched/deadline: dl_release_params() keeps replenished next-period deadline
--

commit 6e0cda7a366c85d079b40022ecc95931ec1d4f8d
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Keep the deadline of a departed constrained task

This patch introduces dl_release_params() and calls it from task_non_contending() and inactive_task_timer() in place of __dl_clear_params() so that a departed constrained SCHED_DEADLINE task keeps its deadline after its bandwidth is released.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index c88cac6bc5fe7..422a8120454a3 100644

[ ... ]

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

Quoted 9 lines
kernel/sched/deadline.c +1 -1
@@ -2341,7 +2342,7 @@ static enum hrtimer_restart inactive_task_timer(struct hrtimer *timer)
 		raw_spin_lock(&dl_b->lock);
 		__dl_sub(dl_b, p->dl.dl_bw, dl_bw_cpus(task_cpu(p)));
 		raw_spin_unlock(&dl_b->lock);
-		__dl_clear_params(dl_se);
+		dl_release_params(dl_se);
 
 		goto unlock;
 	}

[Severity: Medium]
Can a race between inactive_task_timer() and task_non_contending() call dl_release_params() twice and wipe the preserved deadline?

CPU0 CPU1
inactive_task_timer()
(waits on task_rq_lock)

                                  switched_to_dl()
                                    cancel_inactive_timer() -> -1
                                  switched_from_dl()
                                    task_non_contending(&p->dl, false)
                                      hrtimer_active() is true
                                      dl_release_params(dl_se)
                                        (zeroes dl_deadline/dl_period,
                                         keeps deadline)
                                    task_rq_unlock()

task_rq_lock()
!dl_task(p) is true
dl_release_params(dl_se) <-- wipes deadline to 0

On the second call, dl_deadline and dl_period are both 0, so dl_is_implicit(dl_se) evaluates to true and __dl_clear_params() overwrites the preserved deadline with 0. If the task re-enters SCHED_DEADLINE before its next period, it bypasses dl_check_constrained_dl() throttling and can exceed its reserved bandwidth.

Returning early when !dl_se->dl_runtime in dl_release_params() or inactive_task_timer() would keep parameter release idempotent.

[Severity: Medium]
When a throttled constrained task leaves SCHED_DEADLINE with an overrun, does inactive_task_timer() preserve the replenished next-period deadline with zero runtime?

When dl_se->runtime < 0, dl_time_to_zerolag() places the 0-lag time strictly after dl_next_period(dl_se). At dl_next_period(dl_se), dl_task_timer() fires first and calls replenish_dl_entity(), advancing dl_se->deadline into the next period.

When inactive_task_timer() then runs at the 0-lag time, dl_release_params() clears dl_se->runtime to 0 while keeping that next-period deadline. If the task re-enters SCHED_DEADLINE during that next period after already waiting out its previous period and overrun, it has zero runtime and is throttled for an entire extra period.

[ ... ]

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

Quoted 10 lines
kernel/sched/deadline.c +2 -1
@@ -3682,7 +3683,8 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 	 * the "inactive timer" fires, it can continue to consume its current
 	 * runtime using its current deadline. If it stays outside of
 	 * SCHED_DEADLINE until the 0-lag time passes, inactive_task_timer()
-	 * will reset the task parameters.
+	 * will reset the task parameters. A constrained task keeps its
+	 * deadline: see dl_release_params().
 	 */
 	if (task_on_rq_queued(p) && p->dl.dl_runtime)
 		task_non_contending(&p->dl, false);

[Severity: High]
Does switched_from_dl() immediately wipe the deadline that dl_release_params() just preserved for a queued constrained task?

When a queued constrained task leaves SCHED_DEADLINE after its 0-lag time has passed, task_non_contending(&p->dl, false) calls dl_release_params(), which zeroes p->dl.dl_runtime while keeping p->dl.deadline. The block right below then sees !p->dl.dl_runtime and clears p->dl.deadline back to 0:

kernel/sched/deadline.c:switched_from_dl() {
	...
	if (task_on_rq_queued(p) && p->dl.dl_runtime)
		task_non_contending(&p->dl, false);
	...
	if (!p->dl.dl_runtime) {
		p->dl.deadline = 0;
		p->dl.runtime = 0;
	}
}

Without its deadline, re-entering SCHED_DEADLINE before the next period immediately starts a new period with full runtime, allowing the task to exceed its reserved bandwidth. Moving the !p->dl.dl_runtime reset for PI-boosted tasks above task_non_contending() would avoid wiping it.

[ ... ]

Quoted 16 lines
kernel/sched/deadline.c +12 -0
@@ -4155,6 +4157,29 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se)
 	dl_se->dl_bw_oncpu		= 0;
 }
 
+/*
+ * Clear the parameters of a task which left the class, once its
+ * bandwidth is released. A task with a constrained deadline keeps its
+ * deadline. Leaving the class and coming back before its next period
+ * then gives it no new runtime. Back in the class, it waits for that
+ * period, as a task asleep in the class does:
+ * - between its deadline and its next period, dl_check_constrained_dl()
+ *   throttles it;
+ * - before its deadline, it has no runtime left.
+ *
+ * An implicit deadline task keeps nothing. In the class too, a wakeup
+ * after its 0-lag time starts a new period.

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

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+ */
+static void dl_release_params(struct sched_dl_entity *dl_se)
+{
+	u64 deadline = dl_se->deadline;
+	bool constrained = !dl_is_implicit(dl_se);
+
+	__dl_clear_params(dl_se);
+	if (constrained)
+		dl_se->deadline = deadline;
+}

[Severity: Medium]
Can keeping a future dl_se->deadline with runtime == 0 break priority inheritance when the departed task is later boosted while asleep?

For a constrained task whose 0-lag time precedes its absolute deadline, dl_release_params() leaves a non-DL task with dl_runtime == 0, runtime == 0, and a future dl_se->deadline. If a short-deadline waiter boosts the task while it is asleep, rt_mutex_setprio() sets pi_se and ENQUEUE_REPLENISH, but sched_change_end() skips the enqueue because the task is not queued.

When the task wakes up before its preserved deadline, update_dl_entity() sees dl_time_before(dl_se->deadline, rq_clock(rq)) is false and dl_entity_overflow() is false (because runtime == 0 makes left == 0). It skips replenish_dl_new_period() and enqueues the boosted task onto dl_rq with its stale future deadline and zero runtime instead of the donor's earlier deadline, causing priority inversion and deadline misses for the donor.

[Severity: Medium]
Does retaining dl_se->deadline indefinitely without clearing it on re-entry corrupt period calculations when the task returns with a longer dl_period?

Nothing clears the preserved deadline after the old period expires, and __setparam_dl() installs new dl_deadline and dl_period values without resetting it. If a task that ran a short constrained period (such as 10ms) re-enters seconds later with a longer dl_period (such as 4000ms), dl_next_period() combines the stale deadline with the new dl_period and produces a timestamp still in the future.

On wakeup, dl_check_constrained_dl() then spuriously throttles the task for up to the new dl_period even though its old period ended seconds earlier. If the task instead re-enters asleep and switches back to SCHED_OTHER without running, dl_time_to_zerolag() sees the future dl_next_period(), arms inactive_timer, and pins the newly admitted bandwidth in total_bw.

[Severity: Medium]
When a departed constrained task re-enters SCHED_DEADLINE before its preserved future deadline, does runtime == 0 let it run unbudgeted and trigger spurious overruns?

If the task's 0-lag time passed before dl_se->deadline (for example, 10ms runtime, 50ms deadline, 100ms period after running 1ms gives a 0-lag time of 10ms), dl_release_params() leaves a future deadline with runtime == 0 and dl_throttled == 0. Re-entering SCHED_DEADLINE before that deadline skips both dl_check_constrained_dl() and update_dl_entity(), so enqueue_dl_entity() queues the task unthrottled with zero runtime.

When scheduled, the task executes unbudgeted until the next tick or hrtick, accumulates negative runtime debt in update_curr_dl_se(), and spuriously sets dl_overrun (delivering SIGXCPU under SCHED_FLAG_DL_OVERRUN). Even with the zero-runtime throttling added later in commit "sched/deadline:
Keep the debt of a task across a change of parameters", re-entering with a shorter period where dl_next_period(dl_se) <= rq_clock < dl_se->deadline still clears dl_throttled without replenishing when start_dl_timer() returns 0 and enqueues the task with zero runtime.

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

Re: [PATCH v14 09/39] sched/deadline: Keep departing bandwidth across a root domain rebuild

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] sched/deadline: global raw spinlock held across all root domains in dl_clear_root_domains()…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] sched/deadline: global raw spinlock held across all root domains in dl_clear_root_domains()
- [Medium] sched/deadline: global dl_departed_lock wraps dl_b->lock and __dl_update()
- [Medium] sched/deadline: departed bw misattributed in dl_clear_root_domains()
--

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

sched/deadline: Keep departing bandwidth across a root domain rebuild

This commit tracks tasks that leave SCHED_DEADLINE or exit before their 0-lag time on a global dl_departed_list with their departing CPU and a rebuild generation counter, so root domain accounting rebuilds and inactive_task_timer() account their bandwidth against the right root domain.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 422a8120454a3..7d1e305049c25 100644

[ ... ]

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+static void dl_task_release_bw(struct task_struct *p, int cpu)
+{
+	struct sched_dl_entity *dl_se = &p->dl;
+	struct dl_bw *dl_b;
+
+	lockdep_assert_irqs_disabled();
+	guard(raw_spinlock)(&dl_departed_lock);
+	if (dl_se->dl_departed_cpu >= 0) {
+		cpu = dl_se->dl_departed_cpu;
+		dl_se->dl_departed_cpu = -1;

kernel/sched/deadline.c __dl_overflow(struct dl_bw *dl_b, unsigned long cap, u64 old_bw, u64 new_bw) · line 330

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+		list_del_init(&dl_se->dl_departed_node);
+	}
+	if (dl_se->dl_bw_gen == dl_bw_gen) {
+		dl_b = dl_bw_of(cpu);
+		raw_spin_lock(&dl_b->lock);
+		__dl_sub(dl_b, dl_se->dl_bw, dl_bw_cpus(cpu));
+		raw_spin_unlock(&dl_b->lock);
+	}
+	dl_se->dl_bw_gen = dl_bw_gen;
+}

[Severity: Medium]
Can holding the global raw spinlock dl_departed_lock across dl_b->lock and __dl_sub() -> __dl_update() stall unrelated root domains?

Previously, bandwidth accounting was isolated per root domain via rd->dl_bw.lock. Now dl_task_release_bw() holds dl_departed_lock while __dl_update() loops over every active CPU in rd->span touching remote rq->dl.extra_bw cachelines.

sched_dl_overflow() also acquires dl_departed_lock unconditionally on every entry into SCHED_DEADLINE (even when dl_departed_cpu < 0) and holds it across dl_b->lock, dl_bw_capacity(), and __dl_update().

When a large housekeeping root domain runs sched_dl_overflow() or releases departed bandwidth, inactive_task_timer() hardirqs in an unrelated isolated RT partition spin on dl_departed_lock with rq->__lock held and IRQs disabled.

[ ... ]

Quoted 17 lines
kernel/sched/deadline.c +10 -2
@@ -3670,9 +3805,51 @@ void dl_clear_root_domain(struct root_domain *rd)
 		dl_server_add_bw(rd, i);
 }
 
-void dl_clear_root_domain_cpu(int cpu)
+/*
+ * Clear every root domain before a rebuild of their accounting, and count
+ * the rebuild in dl_bw_gen. Put back the bandwidth of their servers. Put
+ * back the bandwidth of the tasks on dl_departed_list, which no cpuset
+ * holds as deadline tasks. Put each in the root domain of the CPU
+ * recorded for it, or drop it if that CPU is not active.
+ * dl_add_task_root_domain() then adds the deadline tasks of the cpusets.
+ */
+void dl_clear_root_domains(void)
 {
-	dl_clear_root_domain(cpu_rq(cpu)->rd);
+	struct sched_dl_entity *dl_se;

kernel/sched/deadline.c void dl_clear_root_domain(struct root_domain *rd) · line 3828

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+	u64 cookie = ++dl_cookie;
+	struct dl_bw *dl_b;
+	int cpu;
+
+	guard(raw_spinlock_irqsave)(&dl_departed_lock);
+	dl_bw_gen++;
+	for_each_possible_cpu(cpu) {
+		if (!dl_bw_visited(cpu, cookie))
+			dl_clear_root_domain(cpu_rq(cpu)->rd);
+	}

[Severity: Medium]
Does holding dl_departed_lock with IRQs disabled across all root domains here introduce long IRQ-off stalls on large SMP systems?

Previously, dl_rebuild_rd_accounting() walked root domains with IRQs enabled and locked each rd->dl_bw.lock separately. Now one raw_spinlock_irqsave section spans every root domain's O(|rd->span|^2) dl_server_add_bw() -> __dl_update() loop plus the dl_departed_list walk.

During a cpuset partition change or CPU hotplug, this creates a long non-preemptible IRQ-off stall (even on PREEMPT_RT) and stalls unrelated isolated RT partitions whenever their CPUs hit dl_departed_lock from inactive_task_timer() or switched_from_dl() while holding rq->__lock.

Quoted 15 lines
kernel/sched/deadline.c +15 -0
+	list_for_each_entry(dl_se, &dl_departed_list, dl_departed_node) {
+		cpu = dl_se->dl_departed_cpu;
+		/*
+		 * Skip bandwidth that an earlier rebuild dropped. It is not
+		 * counted now, and its release removes nothing
+		 * (dl_task_release_bw()).
+		 */
+		if (dl_se->dl_bw_gen != dl_bw_gen - 1)
+			continue;
+		/*
+		 * Drop the bandwidth of a task whose CPU is inactive. A CPU
+		 * that goes offline is in the default root domain by then.
+		 * The root domain that counted the task cannot be found
+		 * from the recorded number. The release then removes
+		 * nothing, and no later rebuild restores it.

kernel/sched/deadline.c void dl_clear_root_domain(struct root_domain *rd) · line 3853

Quoted 10 lines
kernel/sched/deadline.c +9 -0
+		 */
+		if (!cpu_active(cpu))
+			continue;
+		dl_b = dl_bw_of(cpu);
+		raw_spin_lock(&dl_b->lock);
+		__dl_add(dl_b, dl_se->dl_bw, dl_bw_cpus(cpu));
+		raw_spin_unlock(&dl_b->lock);
+		dl_se->dl_bw_gen = dl_bw_gen;
+	}
 }

[Severity: Medium]
Will splitting a CPU into a child cpuset partition root misattribute departed bandwidth and wrap rq->dl.extra_bw below zero?

dl_task_depart() records only task_cpu(p) in dl_departed_cpu, and dl_clear_root_domains() charges dl_se->dl_bw to dl_bw_of(dl_departed_cpu) whenever that CPU is active.

If two 60% deadline tasks on CPUs 0-2 leave SCHED_DEADLINE or exit on CPU 2, and CPU 2 is split into a 1-CPU child partition root before their 0-lag timers fire, both tasks' bandwidth is charged to the child partition instead of the original root domain.

Until inactive_task_timer() fires, the original root domain can over-admit deadline tasks while the child partition rejects valid admissions. Worse, __dl_add() -> __dl_update() subtracts the misattributed bandwidth from the unsigned u64 rq->dl.extra_bw, wrapping it near U64_MAX.

While rq->dl.extra_bw is wrapped, grub_reclaim() sees u_inact + rq->dl.extra_bw > rq->dl.max_bw - dl_se->dl_bw as true and grants maximum GRUB reclamation to SCHED_FLAG_RECLAIM tasks in the overcommitted partition.

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

Re: [PATCH v14 10/39] sched/deadline: Rebuild the root domains' accounting from the task list

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] sched/deadline: O(all threads) walk under tasklist_lock in dl_rebuild_rd_accounting() - [Low]…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] sched/deadline: O(all threads) walk under tasklist_lock in dl_rebuild_rd_accounting()
- [Low] sched/deadline: dead src_cs_head, stale cpuset_locked name, leftover externs
- [Low] sched: stale cpuset_locked name and lock comments in __sched_setscheduler()
- [Low] sched/deadline: data race on p->dl.dl_bw in dl_add_task_root_domain()
--

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

sched/deadline: Rebuild the root domains' accounting from the task list

This commit replaces the cpuset-based walk in dl_rebuild_rd_accounting() with a tasklist walk gated by a global count of bandwidth-holding deadline tasks (dl_nr_bw_tasks), and adds dl_accounting_mutex to serialize admissions against rebuilds when CONFIG_CPUSETS is disabled.

Quoted 4 lines
kernel/cgroup/cpuset.c +0 -0
index 4159abfbbbb53..7628cf77bdfd2 100644

[ ... ]

Quoted 12 lines
kernel/cgroup/cpuset.c +1 -3
@@ -3181,9 +3119,7 @@ static void clear_attach_data(struct llist_head *head, bool cancel)
 	llist_for_each_entry_safe(cs, next, lnode, attach_node) {
 		init_llist_node(&cs->attach_node);
 		if (cs->nr_migrate_dl_tasks) {
-			if (!cancel)
-				atomic_add(cs->nr_migrate_dl_tasks, &cs->nr_deadline_tasks);
-			else if (cs->dl_bw_cpu >= 0) /* && cancel */
+			if (cancel && cs->dl_bw_cpu >= 0)
 				dl_bw_free(cs->dl_bw_cpu, cs->sum_migrate_dl_bw);
 			cs->nr_migrate_dl_tasks = 0;
 			cs->sum_migrate_dl_bw = 0;

kernel/cgroup/cpuset.c static int cpuset_can_attach(struct cgroup_taskset *tset) · line 3213

Quoted 7 lines
kernel/cgroup/cpuset.c +0 -1
@@ -3272,7 +3208,6 @@ static int cpuset_can_attach(struct cgroup_taskset *tset)
 			 * contribute to sum_migrate_dl_bw.
 			 */
 			cs->nr_migrate_dl_tasks++;
-			oldcs->nr_migrate_dl_tasks--;
 			if (dl_task_needs_bw_move(task, cs->effective_cpus))
 				cs->sum_migrate_dl_bw += task->dl.dl_bw;
 		}

[Severity: Low]
Can src_cs_head be removed now that nr_deadline_tasks and oldcs->nr_migrate_dl_tasks-- are gone? cpuset_can_attach_check() still adds oldcs to src_cs_head, and clear_attach_data() only unlinks it without reading or updating any source-cpuset state.

Separately, dl_add_task_root_domain(), dl_clear_root_domain(), and dl_clear_root_domains() in include/linux/sched/deadline.h no longer have callers outside kernel/sched/deadline.c and can be made static.

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 7d1e305049c25..889a70314918c 100644

[ ... ]

Quoted 5 lines
kernel/sched/deadline.c +0 -1
@@ -3712,7 +3728,13 @@ void dl_add_task_root_domain(struct task_struct *p)
 	struct cpumask *msk;
 
 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
-	if (!dl_task(p) || dl_entity_is_special(&p->dl)) {

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

Quoted 10 lines
kernel/sched/deadline.c +7 -0
+	/*
+	 * Count nothing for a special entity, or for a task with no
+	 * bandwidth. The walk of the task list also finds exited tasks. An
+	 * exited task whose bandwidth went with its parameters has a dl_bw
+	 * of 0.
+	 */
+	if (!dl_task(p) || dl_entity_is_special(&p->dl) || !p->dl.dl_bw) {
 		raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
 		return;
 	}

[Severity: Low]
Can the unmarked reads of p->dl.flags and p->dl.dl_bw here race with __dl_clear_params()?

CPU0 CPU1
__schedule() dl_rebuild_rd_accounting()
dequeue_task_dl() dl_add_task_root_domain(p)

    dequeue_dl_entity()               raw_spin_lock_irqsave(&p->pi_lock)
      task_non_contending()
        dl_task_release_bw()
        dl_release_params()
          __dl_clear_params()
            dl_se->flags = 0;         if (... || dl_entity_is_special(&p->dl)
            dl_se->dl_bw = 0;             || !p->dl.dl_bw)  <-- data race

When a dying deadline task past its 0-lag time runs task_non_contending(), __dl_clear_params() writes dl_se->flags and 64-bit dl_se->dl_bw under only rq->__lock after dl_task_release_bw() has dropped dl_departed_lock. Meanwhile dl_add_task_root_domain() holds only p->pi_lock, so KCSAN can flag a data race and 32-bit architectures can observe torn 64-bit reads.

Later patches in this series (commit "sched/deadline: Record the root domain holding a task's bandwidth" and commit "sched/deadline: Leave a dying task out of a rebuild of the accounting") prevent bandwidth corruption here, though the unmarked accesses remain.

Using READ_ONCE()/WRITE_ONCE() on dl_bw and flags, or moving the !p->dl.dl_bw check under dl_departed_lock, would avoid the race.

[ ... ]

Quoted 24 lines
kernel/sched/deadline.c +24 -0
+void dl_rebuild_rd_accounting(void)
+{
+	struct task_struct *g, *p;
+
+	lockdep_assert_cpus_held();
+	lockdep_assert_held(&sched_domains_mutex);
+	lockdep_assert_cpuset_lock_held();
+	lockdep_assert_dl_accounting_held();
+
+	dl_clear_root_domains();
+
+	/*
+	 * Without a task that holds a bandwidth, there is nothing to count.
+	 * The walk would still visit every thread of the system. A CPU
+	 * that goes offline or comes back runs a rebuild, so a suspend and
+	 * a resume run one for each CPU. A task gets a bandwidth under the
+	 * locks this rebuild holds, so the count cannot leave 0 meanwhile.
+	 */
+	if (!atomic_read(&dl_nr_bw_tasks))
+		return;
+
+	read_lock(&tasklist_lock);
+	for_each_process_thread(g, p) {
+		/*

kernel/sched/deadline.c void dl_clear_root_domain(struct root_domain *rd) · line 3903

Quoted 10 lines
kernel/sched/deadline.c +10 -0
+		 * Test the class without the task's locks, and take them only
+		 * for a deadline task. A task enters the class under the locks
+		 * this rebuild holds, or by a boost. A boost brings no
+		 * bandwidth of its own to count.
+		 */
+		if (dl_task(p))
+			dl_add_task_root_domain(p);
+	}
+	read_unlock(&tasklist_lock);
+}

[Severity: Medium]
Does holding read_lock(&tasklist_lock) across for_each_process_thread() here introduce a latency and lock-contention regression when a deadline task is active?

With CONFIG_CPUSETS, rebuilds previously skipped cpusets with no deadline tasks and never took tasklist_lock. Now, as long as even one task holds deadline bandwidth (including a departed task waiting on its 0-lag timer), every CPU hotplug or suspend/resume rebuild walks every thread in the system with read_lock(&tasklist_lock) held.

On non-PREEMPT_RT kernels that disables preemption for milliseconds (0.7 to 1.2 ms per rebuild on 10,000 threads) and stalls write_lock_irq(&tasklist_lock) callers such as copy_process() and exit paths, multiplied across every CPU on suspend and resume.

Tracking bandwidth-holding sched_dl_entity objects on a dedicated list updated in __setparam_dl() and __dl_clear_params() would keep rebuilds O(deadline tasks) without taking tasklist_lock.

kernel/sched/syscalls.c int __sched_setscheduler(struct task_struct *p, · line 572

Quoted 10 lines
kernel/sched/syscalls.c +1 -0
index 595bdb9bd04f3..145940d0ce4de 100644
@@ -568,6 +568,7 @@ int __sched_setscheduler(struct task_struct *p,
 	if (pi && (dl_policy(policy) || dl_policy(p->policy))) {
 		cpuset_locked = true;
 		cpuset_lock();
+		dl_accounting_lock();
 	}

[Severity: Low]
This isn't a bug, but cpuset_locked now tracks dl_accounting_lock() as well (and only dl_accounting_mutex without CONFIG_CPUSETS). Renaming it to dl_accounting_locked and updating the cpuset_mutex-only comments in __sched_setscheduler() would keep the locking documentation accurate.

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

Re: [PATCH v14 14/39] selftests/sched: Test the root domain rebuild in deadline_bw_test

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] selftests/sched: new hotplug cases skip ext_switched_all() guard - [Medium] selftests/sched…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] selftests/sched: new hotplug cases skip ext_switched_all() guard
- [Medium] selftests/sched: unchecked probe(NULL) errors and headroom in new cases
- [Medium] selftests/sched: hotplug_no_admission_pinned() lacks sysctl restore retry
- [Low] selftests/sched: open-coded bandwidth ratio instead of bw_of() --

commit 4704c1b4ece058292b4a960cd1fa4ee1620d2f70
Author: Mathieu Desnoyers <[email protected]>

selftests/sched: Test the root domain rebuild in deadline_bw_test

This commit adds seven test cases to deadline_bw_test covering root domain accounting rebuilds during CPU hotplug, zombie deadline tasks, departed priority-inheritance owners, and sched_setaffinity() racing with sched_setattr().

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
index 6ff9da9644030..ba2a18f354d44 100644

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static void cpu_up(int cpu) · line 4688

Quoted 11 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +11 -0
+static int hotplug_sleeper_switched(void)
+{
+	int base = probe(NULL), base_off, after, cpu, ret = KSFT_PASS;
+	pid_t pid;
+
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("CPU %d cannot go offline\n", hp_cpu);
+		cpu_up(hp_cpu);
+		return KSFT_SKIP;
+	}
+	base_off = probe(NULL);

[Severity: Medium]
Can unchecked probe(NULL) errors cause false passes or wrong skips here?

probe(NULL) returns -1 on internal failure, such as disabled admission control hitting the thread limit. Because hotplug_sleeper_switched(), hotplug_no_admission_pinned(), and affinity_vs_setattr() never check for < 0, repeated -1 returns compare equal and report KSFT_PASS.

In hotplug_sleepers() and hotplug_departed(), a -1 return falls into the insufficient-room check and reports KSFT_SKIP instead of KSFT_FAIL.

Separately, hotplug_sleeper_switched() omits a base_off < 3 check for its 30% sleeper, and hotplug_departed() checks base_off <= 0 instead of base_off < 4 for its 40% task. On a tight sched_rt_runtime_us, cpu_online(..., 0) can return -EBUSY and fail instead of skipping.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static void cpu_up(int cpu) · line 4790

Quoted 8 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +8 -0
+out:
+	cpu_up(hp_cpu);
+	reap(pid);
+	if (write_file("/proc/sys/kernel", "sched_rt_runtime_us", saved)) {
+		ksft_print_msg("admission control cannot be turned on again\n");
+		return KSFT_FAIL;
+	}
+	sleep_ns(3 * PERIOD);

[Severity: Medium]
What happens if restoring sched_rt_runtime_us fails with -EBUSY before the killed 50% task reaches its 0-lag time?

When free headroom is under 50% (or cpu_up(hp_cpu) fails), sched_dl_global_validate() rejects the write because dl_b->total_bw still counts the departing task, and sched_rt_handler() rolls sched_rt_runtime_us back to -1.

Because hotplug_no_admission_pinned() returns immediately without sleeping 3 * PERIOD or polling with wait_for() as server_restore() does, admission control stays permanently at -1 for the rest of hp_cases[] and on the host after the test exits.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c

Quoted 1 line
tools/testing/selftests/sched/deadline/deadline_bw_test.c +1 -0
+	bw = (ZOMBIE_RUNTIME << 20) / ZOMBIE_PERIOD;	/* as to_ratio() */

[Severity: Low]
This isn't a bug, but both death_zombie_hotplug() and pi_departed_moved() open-code this ratio instead of reusing the existing bw_of(ZOMBIE_RUNTIME, ZOMBIE_PERIOD) helper.

[ ... ]

Quoted 12 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +1 -0
@@ -4790,6 +5429,7 @@ static const struct p_case {
 	{ "death_pi_deadline_owner", death_pi_deadline_owner, MEASURED_IN_P },
 	{ "death_group", death_group, MEASURED_IN_P },
 	{ "death_zombie_switched", death_zombie_switched, FROM_OUTSIDE },
+	{ "death_zombie_hotplug", death_zombie_hotplug, FROM_OUTSIDE },
 	{ "yield_switched_out", yield_switched_out, IN_P },
 	{ "yield_killed", yield_killed, MEASURED_IN_P },
 	{ "overrun_caught", overrun_caught, IN_P },
@@ -4808,9 +5448,15 @@ static const struct p_case {
 static const struct hp_case {
 	const char *name;
 	int (*fn)(void);

tools/testing/selftests/sched/deadline/deadline_bw_test.c static const struct p_case { · line 5460

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +6 -0
+	int no_hp;		/* takes no CPU offline */
 } hp_cases[] = {
+	{ "hotplug_sleepers", hotplug_sleepers },
+	{ "hotplug_sleeper_switched", hotplug_sleeper_switched },
+	{ "hotplug_no_admission_pinned", hotplug_no_admission_pinned },
 	{ "hotplug_refused", hotplug_refused },
+	{ "hotplug_departed", hotplug_departed },
 	{ "hotplug_server", hotplug_server },
+	{ "affinity_vs_setattr", affinity_vs_setattr, 1 },
 };

[Severity: Medium]
Should death_zombie_hotplug() and the four new hotplug cases in hp_cases[] skip when ext_switched_all() is true, as hotplug_server() does?

With a full-mode sched_ext scheduler lacking ops.cpu_offline, offlining a CPU exits the scheduler in handle_hotplug() and detaches ext_server in favor of fair_server.

Because server_init() latches server_dir to ext_server once at startup, the later server_* cases in p_cases[] (and hotplug_server(), whose own ext_switched_all() guard then returns 0) write to the detached ext_server and fail.

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

Re: [PATCH v14 13/39] selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain rebuild

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] selftests/sched: hardcoded bandwidth thresholds fail on asymmetric CPUs - [Low] selftests/sched…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] selftests/sched: hardcoded bandwidth thresholds fail on asymmetric CPUs
- [Low] selftests/sched: stale cg_q partition skips rebuild in make_partition()
- [Low] selftests/sched: kill() before set_other() in reap() arms 0-lag timer
- [Low] selftests/sched: pick_cpus() truncates CPU mask at CPU_SETSIZE (1024)
--

commit 16912fc7803a3b5fd74783e0eb69b402ea2af6a7
Author: Mathieu Desnoyers <[email protected]>

selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain rebuild

This patch adds deadline_rebuild_test to test that SCHED_DEADLINE bandwidth from departing tasks is accounted correctly across root domain rebuilds and partition moves.

Quoted 6 lines
tools/testing/selftests/sched/deadline/deadline_rebuild_test.c new file +0 -0
new file mode 100644
index 0000000000000..735c3c65e156a
@@ -0,0 +1,587 @@

[ ... ]

tools/testing/selftests/sched/deadline/deadline_rebuild_test.c line 120

Quoted 11 lines
tools/testing/selftests/sched/deadline/deadline_rebuild_test.c new file +11 -0
+static void reap(pid_t pid)
+{
+	int status;
+
+	if (pid <= 0)
+		return;
+	if (kill(pid, SIGKILL) && errno != ESRCH)
+		ksft_print_msg("kill %d: %s\n", pid, strerror(errno));
+	/* Ignore the result: the task may be dead already. */
+	set_other(pid);
+	while (waitpid(pid, &status, 0) != pid) {

[Severity: Low]
Can sending SIGKILL before set_other() in reap() leave a 0-lag reservation behind for the next test case?

In check_p(), sleeper child a is admitted to SCHED_DEADLINE at 600ms/1000ms while paused, so its dl_se->deadline is still 0. Calling kill(a, SIGKILL) first wakes a under SCHED_DEADLINE into a fresh period:

parent child a (on cpu_p)
reap(a)
kill(a, SIGKILL)
enqueue_task_dl() -> new period runs SIGKILL / do_exit() for dt > 0
set_other(a) task_non_contending() -> arms inactive_timer
test_rebuild() skips sleep
...
set_deadline(400ms) <-- EBUSY if timer still armed

Because test_rebuild() clears ran before check_p(), it skips the post-test 1.5s wait before starting switched_out_before_rebuild. If a's inactive timer has not fired by the time the next case requests 400ms/1000ms on cpu_p, admission exceeds P's capacity and fails spuriously with EBUSY.

Calling set_other(pid) before kill(pid, SIGKILL) switches a while dl_se->deadline is still 0, so dl_time_to_zerolag() returns -1 and releases the bandwidth immediately.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_rebuild_test.c line 183

Quoted 10 lines
tools/testing/selftests/sched/deadline/deadline_rebuild_test.c new file +10 -0
+/* Make @cg a partition root of CPU @cpu alone. Return 0, or -1 on error. */
+static int make_partition(const char *cg, int cpu)
+{
+	char path[PATH_MAX + 32], buf[32];
+
+	if (mkdir(cg, 0755) && errno != EEXIST)
+		return -1;
+	snprintf(buf, sizeof(buf), "%d", cpu);
+	if (write_file(cg, "cpuset.cpus", buf) || write_file(cg, "cpuset.cpus.partition", "root"))
+		return -1;

[Severity: Low]
Could tolerating EEXIST here skip the root domain rebuild when a stale cg_q partition is left behind?

If a previous run was interrupted while deadline_rebuild_q existed as an active partition root on cpu_q, both writes become kernel no-ops:
update_cpumask() returns early when the cpumask is unchanged, and update_prstate() returns early when the partition is already a root. test_rebuild(DIES) would then never trigger a rebuild before the 0-lag time and silently pass even on a buggy kernel.

Removing stale cg_p and cg_q directories at startup, or resetting cpuset.cpus.partition to "member" before setting "root", would prevent this.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_rebuild_test.c line 348

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_rebuild_test.c new file +4 -0
+	e1 = set_deadline(a, 600 * NSEC_PER_MSEC);
+	e2 = set_deadline(b, 600 * NSEC_PER_MSEC);
+	if (e1)
+		ksft_print_msg("a first task refused in P: %s\n", strerror(-e1));

[Severity: Medium]
Will this hardcoded 600ms/1000ms threshold cause false failures on asymmetric CPUs?

pick_cpus() always selects the highest online non-isolated CPU for cpu_p, which on asymmetric topologies such as Intel hybrid or ARM big.LITTLE is often a lower-capacity core. Because __dl_overflow() scales dl_b->bw by cpu_p's capacity, a one-CPU partition on a core with capacity below roughly 680/1024 cannot admit 600ms/1000ms after the default 95% RT cap and 5% fair_server, so the first set_deadline() fails with EBUSY on a healthy kernel.

Separately, main() only skips when sched_rt_runtime_us is negative; when sched_rt_runtime_us is 0 or the RT runtime ratio is too small for the hardcoded 400ms and 600ms runtimes, the test fails instead of skipping. Probing or scaling runtimes to P's available capacity, or skipping when P cannot admit the required bandwidth, would avoid these false failures.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_rebuild_test.c line 500

Quoted 11 lines
tools/testing/selftests/sched/deadline/deadline_rebuild_test.c new file +11 -0
+static int pick_cpus(void)
+{
+	static char online[CPU_SETSIZE], isol[CPU_SETSIZE];
+	char buf[4096];
+	int cpu, n = 0;
+
+	if (read_file("/sys/devices/system/cpu/online", buf, sizeof(buf)))
+		return 0;
+	parse_cpulist(buf, online, CPU_SETSIZE);
+	if (!read_file("/sys/devices/system/cpu/isolated", buf, sizeof(buf)))
+		parse_cpulist(buf, isol, CPU_SETSIZE);

[Severity: Low]
Does capping online[], isol[], and hk_set at CPU_SETSIZE (1024) break moved_after_switch_out on systems with online CPUs >= 1024?

When main() passes sizeof(hk_set) to sched_setaffinity(), get_user_cpu_mask() clears every CPU bit >= 1024 in the test process and its children. In test_move(), the child forked outside P inherits that truncated cpus_mask, which no longer covers the online non-isolated CPUs

Quoted 1 line

= 1024 in the root domain span, so __sched_setscheduler() rejects

SCHED_DEADLINE with EPERM and the test fails.

Sizing the mask dynamically with CPU_ALLOC() and CPU_ALLOC_SIZE() from the highest online CPU would avoid truncating the affinity mask.

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

Re: [PATCH v14 12/39] sched/deadline: Leave a dying task out of a rebuild of the accounting

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] sched/deadline: double dl_release_params() wipes constrained deadline --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] sched/deadline: double dl_release_params() wipes constrained deadline
--

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

sched/deadline: Leave a dying task out of a rebuild of the accounting

This commit skips dead deadline tasks with no recorded dl_bw_cpu in dl_add_task_root_domain() so a root domain rebuild does not re-count bandwidth that was already released before dl_bw was cleared.

Quoted 12 lines
kernel/sched/deadline.c +4 -0
index 03a6699151cfe..fc0f32a7f80ac 100644
@@ -3861,6 +3861,17 @@ void dl_add_task_root_domain(struct task_struct *p)
 		if (recorded < 0 || !cpu_active(recorded))
 			goto unlock;
 		cpu = recorded;
+	} else if (READ_ONCE(p->__state) == TASK_DEAD && p->dl.dl_bw_cpu < 0) {
+		/*
+		 * Count nothing for a dead task with no record. Its last
+		 * schedule released the bandwidth under its rq lock, and has

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

Quoted 10 lines
kernel/sched/deadline.c +7 -0
+		 * not cleared dl_bw yet. The release clears the record under
+		 * dl_departed_lock, which this walk holds. A dead task with a
+		 * record has not reached its last schedule. Count it as a
+		 * live task. That schedule then releases what the walk
+		 * counted, or puts the task on the departed list.
+		 */
+		goto unlock;
 	}
 	rq = cpu_rq(cpu);
 	dl_b = &rq->rd->dl_bw;

[Severity: Medium]
In commit "sched/deadline: Keep the deadline of a departed constrained task", can a second call to dl_release_params() wipe the preserved dl_se->deadline of a constrained-deadline task?

When a constrained-deadline task has an armed inactive_timer that starts running on CPU1 (making hrtimer_active() return true) before acquiring task_rq_lock(), CPU0 can wake or PI-boost the task and leave SCHED_DEADLINE via switched_from_dl() -> task_non_contending() first:

CPU0 CPU1
inactive_task_timer()
(hrtimer_active() is true)
switched_from_dl()
task_non_contending(..., false)

    hrtimer_active() -> true
    dl_task_release_bw(p)
    dl_release_params(dl_se)
      __dl_clear_params(dl_se)
      dl_se->deadline = deadline
                                      task_rq_lock(p, &rf)
                                      !dl_task(p) -> true
                                      dl_task_release_bw(p)
                                      dl_release_params(dl_se)
                                        dl_is_implicit() -> true (0 == 0)
                                        __dl_clear_params(dl_se)
                                          <-- dl_se->deadline wiped to 0

On the second call to dl_release_params(), dl_deadline and dl_period are both 0, so dl_is_implicit() evaluates to true and __dl_clear_params() overwrites the preserved dl_se->deadline with 0.

If the task re-enters SCHED_DEADLINE before its next period, it bypasses dl_check_constrained_dl() throttling and can consume more than its admitted bandwidth, potentially causing other deadline tasks to miss deadlines.

Returning early from dl_release_params() when dl_se->dl_runtime is already 0 would avoid wiping the preserved deadline.

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

Re: [PATCH v14 16/39] cgroup/cpuset: Wait for an attach before rebuilding the sched domains

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] cgroup/cpuset: duplicated cpuset_full_lock() in cpuset write handlers - [Low] cgroup/cpuset: commit…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] cgroup/cpuset: duplicated cpuset_full_lock() in cpuset write handlers
- [Low] cgroup/cpuset: commit message inaccurately claims CPU hotplug never waits
--

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

cgroup/cpuset: Wait for an attach before rebuilding the sched domains

This commit updates cpuset_full_lock() and rebuild_sched_domains_cpuslocked() to call wait_attach_done_lock() instead of mutex_lock(&cpuset_mutex), preventing sched domain rebuilds from dropping deadline bandwidth reservations made during a cpuset attach.

Quoted 5 lines

Fix this by waiting for an attach in progress in rebuild_sched_domains_cpuslocked() and in cpuset_full_lock(). The latter then takes its locks in the order of the writes of cpus and cpus.partition. Two kinds of callers never wait:
- a rebuild from CPU hotplug finds no attach in progress;

[Severity: Low]
Is the claim that a rebuild from CPU hotplug never waits accurate?

cpuset_can_fork() also increments attach_ctx.in_progress on CLONE_INTO_CGROUP without holding cpus_read_lock(). CPU hotplug reaching rebuild_sched_domains_cpuslocked() can therefore wait for cpuset_fork() or cpuset_cancel_fork() to finish.

Memory hotplug via cpuset_track_online_nodes() also calls cpuset_handle_hotplug() under cpus_read_lock(), so it can wait on regular attach migrations when subpartitions_cpus is non-empty.

[ ... ]

Quoted 15 lines
kernel/cgroup/cpuset.c +2 -1
index 194a438e25c31..51b6be4607946 100644
@@ -296,17 +296,20 @@ void lockdep_assert_cpuset_lock_held(void)
 	lockdep_assert_held(&cpuset_mutex);
 }
 
+static void wait_attach_done_lock(void) __acquires(&cpuset_mutex);
+
 /**
  * cpuset_full_lock - Acquire full protection for cpuset modification
  *
  * Takes both CPU hotplug read lock (cpus_read_lock()) and cpuset mutex
- * to safely modify cpuset data.

kernel/cgroup/cpuset.c void lockdep_assert_cpuset_lock_held(void) · line 313

Quoted 10 lines
kernel/cgroup/cpuset.c +3 -1
+ * to safely modify cpuset data. Waits for an attach in progress before
+ * it takes cpuset mutex.
  */
 void cpuset_full_lock(void)
 {
 	mutex_lock(&cpuset_top_mutex);
 	cpus_read_lock();
-	mutex_lock(&cpuset_mutex);
+	wait_attach_done_lock();
 }

[Severity: Low]
Now that cpuset_full_lock() runs this three-step sequence, can cpuset_write_resmask() and cpuset_partition_write() call it instead of open-coding the same locks? Duplicating the sequence risks future divergence if the cpuset full-locking order changes.

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

Re: [PATCH v14 26/39] selftests/sched: Test the root domain of a task in deadline_bw_test

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 11 potential issues to consider: - [Low] selftests/sched: stack buffer overflow in rebuild_record_taken() - [Low] selftests/sched: unchecked…

Thank you for your contribution! Sashiko AI review found 11 potential issues to consider:
- [Low] selftests/sched: stack buffer overflow in rebuild_record_taken()
- [Low] selftests/sched: unchecked buffer truncation in partition_invalidate_refused()
- [Low] selftests/sched: unclosed ack[1] pipe end hangs two partition tests
- [Low] selftests/sched: inverted tell flag in partition_swap_accepted()
- [Low] selftests/sched: unpinned migration window causes flaky deadline_bw_test cases
- [Low] selftests/sched: silent or misleading KSFT_SKIP returns in deadline_bw_test
- [Low] selftests/sched: wrong isolcpus count comment and cs_setup() duplication
- [Low] selftests/sched: missing ext_switched_all() check before hotplug with server
- [Low] selftests/sched: woken_on() accepts negative task_cpu_of() error as valid CPU
- [Low] selftests/sched: no_admission_affinity_moves() restores sysctl before 0-lag
- [Low] selftests/sched: hotplug_no_admission_pinned() restores sysctl before 0-lag
--

commit 771f314a11047ea4b849341ab0c81a8587315b6a
Author: Mathieu Desnoyers <[email protected]>

selftests/sched: Test the root domain of a task in deadline_bw_test

This commit adds 40 test cases to deadline_bw_test covering CPU hotplug, cpuset partition changes, and root domain accounting for SCHED_DEADLINE tasks with and without isolcpus=domain.

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +0 -0
index f50d45dd57994..8c2a2ccb3c600 100644

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c line 51

Quoted 8 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +1 -1
@@ -45,7 +46,7 @@
  *
  * The test needs root, deadline admission control and 3 housekeeping
  * CPUs. Some cases need 4. Most also need the cgroup v2 cpuset
- * controller. Some need debugfs or CPU hotplug. Five need
+ * controller. Some need debugfs or CPU hotplug. Twenty-nine need
  * isolcpus="domain" at boot.
  */

[Severity: Low]
Should this say thirty-one rather than twenty-nine, given the five existing cases plus the 26 new cases that require isolcpus=domain?

Two other small cleanups in the added code: fallback_case() declares a local cg_q that shadows the file-scope cg_q and duplicates the cgroup setup and teardown from cs_setup()/cs_cleanup(); and hotplug_partition_invalid_refused() leaves cs_n[0] non-zero if snprintf() truncates before jumping to out:, unlike hotplug_sibling_partition_refused() which clears cs_d[0] = 0.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int fallback_wake(int fd, pid_t pid) · line 7118

Quoted 8 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +8 -0
+	snprintf(path, sizeof(path), "%s/cgroup.subtree_control", root);
+	if (read_file(path, buf, sizeof(buf)))
+		return KSFT_SKIP;
+	if (!strstr(buf, "cpuset")) {
+		if (write_file(root, "cgroup.subtree_control", "+cpuset"))
+			return KSFT_SKIP;
+		added = 1;
+	}

[Severity: Low]
Should these early KSFT_SKIP returns print a skip reason? cs_setup() also returns -1 without logging, so the roughly 20 new cases calling it (as well as partition_grows_child_valid() and hotplug_top_last_refused()) skip silently when prerequisites are missing.

In addition, partition_shrink_moves_refused(), partition_shrink_isolated_moves_refused(), partition_invalidate_refused(), and partition_child_invalidate_refused() combine their CPU-count check with cs_setup(), printing a misleading CPU-count message when cs_setup() fails. Most new cases also initialize ret = KSFT_SKIP and only switch to KSFT_FAIL after pipe(fd), so a pipe() error jumps to out: and silently skips instead of failing.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static int fallback_wake(int fd, pid_t pid) · line 7436

Quoted 7 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +7 -0
+out:
+	reap(pid);
+	if (write_file("/proc/sys/kernel", "sched_rt_runtime_us", saved)) {
+		ksft_print_msg("admission control cannot be turned on again\n");
+		return KSFT_FAIL;
+	}
+	sleep_ns(3 * PERIOD);

[Severity: Low]
Can restoring /proc/sys/kernel/sched_rt_runtime_us before sleep_ns(3 * PERIOD) fail with -EBUSY?

While the killed spinning task's 0-lag timer still holds its bandwidth in dl_b->total_bw, sched_dl_global_validate() rejects the write if new_bw * cpus < dl_b->total_bw. That returns KSFT_FAIL immediately and leaves global admission control disabled (-1) for the remaining test cases and after the test exits. Waiting 3 * PERIOD before restoring sched_rt_runtime_us avoids this.

[Severity: Low]
In commit "selftests/sched: Test the root domain rebuild in deadline_bw_test" earlier in this series, does hotplug_no_admission_pinned() have the same ordering problem? Its out: path restores sched_rt_runtime_us immediately after reaping the spinning 50% deadline task and before sleep_ns(3 * PERIOD), which can fail with -EBUSY and leave admission control at -1 for all subsequent cases.

[ ... ]

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

Quoted 7 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +7 -0
+	err = enter(cs_c, pid);
+	cpu = task_cpu_of(pid);
+	if (bw <= 0 || def != def0 || err || cpu != fb_h) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in C: %s, on CPU %d\n",
+			       def - def0, bw, strerror(-err), cpu);
+		goto out;
+	}

[Severity: Low]
Can hotplug_nested_refused() fail spuriously if the child migrates off fb_h before sleeping?

task_from() widens the child's affinity to all CPUs before calling set_deadline() and blocking in read(), so preemption or load balancing can move it to another CPU before it sleeps, and enter() does not migrate a sleeping task's CPU. Unlike fallback_case(), which treats sleeping off fb_h as KSFT_SKIP, hotplug_nested_refused(), hotplug_dead_accepted(), partition_takes_fallback_refused(), partition_swap_refused(), partition_refused_no_warn(), and hotplug_asleep_setattr() all return KSFT_FAIL in that case.

[ ... ]

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

Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +5 -0
+	c = 'x';
+	if (enter(cs_b, pid) || write(go[1], &c, 1) != 1 || read(ack[0], &c, 1) != 1) {
+		ksft_print_msg("the task never ran in B\n");
+		goto out;
+	}

[Severity: Low]
Can read(ack[0], &c, 1) block forever if the child exits before writing to ack[1]?

The parent keeps ack[1] open until out:, so if the child terminates early (for example if read(go[0], &c, 1) fails and it calls _exit(1)), the kernel never delivers EOF on ack[0] and the test hangs until the harness timeout. hotplug_top_last_refused() has the same unclosed ack[1] before read(ack[0], &c, 1). Closing ack[1] and go[0] in the parent right after fork_child() avoids the hang.

[ ... ]

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

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +4 -0
+	if (ic < 0 || x < 0 || !cpu_hotpluggable(x) || !server_found || cs_setup()) {
+		ksft_print_msg("needs isolcpus=\"domain\", 2 housekeeping CPUs, CPU hotplug, fair server files\n");
+		return KSFT_SKIP;
+	}

[Severity: Low]
Should hotplug_isolated_partition_falls_back() also skip when ext_switched_all() is true, like hotplug_server() and hotplug_server_refused()?

Because it reads server_get() and checks totals_check() across cpu_online(x, 0), a CPU hotplug that terminates a sched_ext switch_all=1 scheduler switches accounting from ext_server back to fair_server and causes a spurious failure.

[ ... ]

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

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +4 -0
+	snprintf(buf, sizeof(buf), "%d", h2);
+	if (write_file(cs_q, "cpuset.cpus", buf) || partition_has(cs_q, "invalid", 1) ||
+	    fallback_wake(fd[1], pid))
+		goto out;

[Severity: Low]
Is the tell flag in partition_has(cs_q, "invalid", 1) inverted?

partition_has() only prints cpuset.cpus.partition when the substring is absent and tell is non-zero, so this logs a spurious message on every passing run when Q is "root", stays silent if Q becomes invalid, and omits checking that Q remains "root". Using !partition_has(cs_q, "root", 1) || partition_has(cs_q, "invalid", 0) matches the other valid-partition checks.

[ ... ]

Quoted 4 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +4 -0
+	/* Q has every housekeeping CPU but A, B and D. */
+	for (i = n = 0; i < ncpus - 3; i++)
+		n += snprintf(buf + n, sizeof(buf) - n, "%s%d", n ? "," : "",
+			      online[i]);

[ ... ]

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

Quoted 3 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +3 -0
+	for (i = 1, n = 0; i < ncpus - 3; i++)
+		n += snprintf(buf + n, sizeof(buf) - n, "%d,", online[i]);
+	snprintf(buf + n, sizeof(buf) - n, "%d", d);

[Severity: Low]
Can these snprintf() loops overflow buf[4096] on the stack?

Because snprintf() returns the untruncated length, on a large-CPU system where the formatted CPU list exceeds 4095 bytes, n grows past sizeof(buf) and sizeof(buf) - n underflows size_t on the next iteration or the trailing snprintf(), writing past buf on the stack. Guarding both loops with n < (int)sizeof(buf) and skipping when n >= (int)sizeof(buf) (as mask_grows_refused() does) prevents the overflow.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static const struct p_case { · line 10843

Quoted 6 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +6 -0
+	cpu = task_cpu_of(pid);
+	if (want_isol ? !is_isol(cpu) : want >= 0 ? cpu != want : is_isol(cpu)) {
+		ksft_print_msg("woken on CPU %d\n", cpu);
+		return -1;
+	}
+	return 0;

[Severity: Low]
Does woken_on() accept a -1 error from task_cpu_of() as a valid housekeeping CPU? When called with want_isol == 0 and want < 0 (as in partition_shrink_isolated_moves_refused()), cpu == -1 makes is_isol(-1) return 0, so woken_on() returns 0 instead of -1. Checking cpu < 0 first avoids this.

[ ... ]

tools/testing/selftests/sched/deadline/deadline_bw_test.c static const struct p_case { · line 11066

Quoted 5 lines
tools/testing/selftests/sched/deadline/deadline_bw_test.c +5 -0
+	for (i = 0; i < ncpus && n < (int)sizeof(buf); i++)
+		n += snprintf(buf + n, sizeof(buf) - n, "%s%d", i ? "," : "", online[i]);
+	for (i = 0; i < nisol && n < (int)sizeof(buf); i++)
+		n += snprintf(buf + n, sizeof(buf) - n, ",%d", isol[i]);
+	err = write_file(cs_q, "cpuset.cpus", buf);

[Severity: Low]
Should partition_invalidate_refused() check n >= (int)sizeof(buf) before calling write_file()?

On a host with roughly 540 or more online CPUs, the formatted CPU list truncates at 2048 bytes and write_file() receives a partial or malformed list, causing a spurious KSFT_FAIL instead of skipping.

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

Re: [PATCH v14 28/39] sched/deadline: Cancel the replenishment timer with the parameters

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] sched/deadline: double dl_release_params() wipes constrained task deadline - [Medium]…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] sched/deadline: double dl_release_params() wipes constrained task deadline
- [Medium] sched/deadline: switched_from_dl() zeroes preserved constrained deadline
- [Medium] sched/deadline: dl_task_timer() leaves phantom deadline on departed task
- [Medium] sched/deadline: dl_task_timer() misses stale callback check when boosted
--

commit 3ee57a6bbb822d45131cce62988fa9cdd9ab1948
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Cancel the replenishment timer with the parameters

This commit cancels the replenishment timer alongside parameter release in task_non_contending() and inactive_task_timer() so a task re-entering SCHED_DEADLINE does not inherit a stale timer from its previous reservation.

kernel/sched/deadline.c static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task) · line 787

Quoted 12 lines
kernel/sched/deadline.c +1 -0
index 081c5812a063b..82066b2402a95 100644
@@ -781,6 +781,7 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 				if (dl_task && READ_ONCE(p->__state) == TASK_DEAD)
 					sub_rq_bw(dl_se, &rq->dl);
 				dl_task_release_bw(p);
+				cancel_replenish_timer(dl_se);
 				dl_release_params(dl_se);
 			}
 		}

[Severity: Medium]
Can switched_from_dl() wipe the deadline that dl_release_params() just preserved for a constrained-deadline task?

When a queued constrained-deadline task (such as one that called sched_yield()) leaves SCHED_DEADLINE past its 0-lag time, switched_from_dl() calls task_non_contending(&p->dl, false). That cancels the replenishment timer and calls dl_release_params(), which clears p->dl.dl_runtime to 0 while keeping p->dl.deadline. On return, switched_from_dl() then executes the boosted-task cleanup:

kernel/sched/deadline.c:switched_from_dl() {
	...
	if (task_on_rq_queued(p) && p->dl.dl_runtime)
		task_non_contending(&p->dl, false);
	...
	if (!p->dl.dl_runtime) {
		p->dl.deadline = 0;
		p->dl.runtime = 0;
	}
}

With dl_throttled cleared, the replenishment timer cancelled, and deadline zeroed, re-entering SCHED_DEADLINE before the next period bypasses dl_check_constrained_dl() and grants a fresh period, exceeding the task's admitted bandwidth. Checking !p->dl.dl_runtime before calling task_non_contending() (or using else if) would preserve the deadline.

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

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

[Severity: Medium]
Can a racing inactive_task_timer() call dl_release_params() a second time and wipe a constrained task's preserved deadline?

dl_release_params() is not idempotent: the first call clears dl_deadline and dl_period to 0 while keeping dl_se->deadline, so a second call sees dl_is_implicit(dl_se) as true (0 == 0) and overwrites deadline with 0. This can happen when inactive_task_timer() is waiting on task_rq_lock() as the task wakes and leaves SCHED_DEADLINE:

CPU0 CPU1
---- ----
__run_hrtimer(inactive_timer) inactive_task_timer()
task_rq_lock(p) [waits]
task_contending()
dl_non_contending = 0
cancel_inactive_timer() == -1
switched_from_dl()
task_non_contending(..., false)
hrtimer_active() == true
dl_task_release_bw(p)
cancel_replenish_timer(dl_se)
dl_release_params(dl_se)
dl_deadline = dl_period = 0
rq_unlock()
[acquires rq lock] !dl_task(p) is true dl_release_params(dl_se)
deadline = 0 <-- wipes deadline

Clearing the preserved deadline lets the task bypass dl_check_constrained_dl() if it re-enters SCHED_DEADLINE before its next period, exceeding its admitted bandwidth. In addition, when zerolag_time >= 0 while inactive_task_timer() is running, task_non_contending() releases bandwidth and cancels dl_timer before the new 0-lag time. Guarding dl_release_params() with an early return when !dl_se->dl_runtime would prevent the second call from wiping deadline.

[Severity: Medium]
What happens if dl_task_timer() fires before inactive_task_timer() on a departed constrained-deadline task?

Suppose a constrained-deadline task overruns its runtime (runtime < 0) in period [0, P] and leaves SCHED_DEADLINE before P. Its 0-lag time falls after P, so dl_task_timer() fires first at P; seeing !dl_task(p) and dl_throttled, it calls replenish_dl_entity(dl_se) and advances dl_se->deadline to P + dl_deadline. When inactive_task_timer() later runs at the 0-lag time, cancel_replenish_timer() is a no-op and dl_release_params() clears runtime to 0 while keeping that advanced deadline.

If the task re-enters SCHED_DEADLINE during (0-lag, 2*P) without ever having run in [P, 2*P], it is given zero runtime and throttled for an extra period until 2*P.

[Severity: Medium]
Does cancel_replenish_timer() handle a dl_task_timer() callback that is already running on another CPU?

cancel_replenish_timer() calls hrtimer_try_to_cancel(), which returns -1 if dl_task_timer() is already executing and waiting on task_rq_lock(p). Because __run_hrtimer() already cleared is_queued, a subsequent start_dl_timer() for a new reservation R2 re-arms dl_timer while the stale callback is still pending:

CPU0 CPU1
---- ----
__run_hrtimer(dl_timer)
timer->is_queued = false
dl_task_timer()
task_rq_lock(p) [waits]
inactive_task_timer()
cancel_replenish_timer() == -1 dl_release_params(dl_se) rq_unlock()
p re-enters SCHED_DEADLINE (R2) throttles while blocking ->
start_dl_timer() [queues for T2]
PI-boosted while asleep
[acquires rq lock]
!task_on_rq_queued(p) is true replenish_dl_entity(dl_se) <-- premature replenish

If the PI donor then deboosts the task before T2 and the task wakes up, it runs with unearned runtime while the newer dl_timer remains queued, violating CBS bandwidth guarantees. A later patch in this series, commit "sched/deadline: Keep the debt of a task across a change of parameters", guards the non-boosted case with a dl_next_period(dl_se) check, but skips it when is_dl_boosted(dl_se) is true, leaving this sleeping PI-boosted case exposed. Checking hrtimer_is_queued(timer) under task_rq_lock(p) in dl_task_timer() would reject any stale callback once dl_timer has been re-armed.

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

Re: [PATCH v14 31/39] sched/deadline: Record the start of the period

In reply to Mathieu Desnoyers
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] sched/deadline: switched_from_dl() wipes preserved deadline and period_start - [Medium]…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] sched/deadline: switched_from_dl() wipes preserved deadline and period_start
- [Medium] sched/deadline: double dl_release_params() wipes constrained task period state
--

commit 58b2bd6d3542e44a3b389675f5a1514b5ff34ab8
Author: Mathieu Desnoyers <[email protected]>

sched/deadline: Record the start of the period

This commit adds a period_start field to struct sched_dl_entity and updates or clears it alongside deadline so that a follow-up patch can compute the next period from the period start after sched_setattr().

Quoted 4 lines
kernel/sched/deadline.c +0 -0
index 58fc1c6c41178..820e71ee7fdf0 100644

[ ... ]

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

Quoted 7 lines
kernel/sched/deadline.c +1 -0
@@ -4675,6 +4680,7 @@ static void switched_from_dl(struct rq *rq, struct task_struct *p)
 	 */
 	if (!p->dl.dl_runtime) {
 		p->dl.deadline = 0;
+		p->dl.period_start = 0;
 		p->dl.runtime = 0;
 	}

[Severity: Medium]
Can this block wipe the deadline and period_start that dl_release_params() just preserved for a constrained-deadline task?

When a runnable constrained-deadline task leaves SCHED_DEADLINE past its 0-lag time, switched_from_dl() first calls task_non_contending(), which invokes dl_release_params(). That clears p->dl.dl_runtime to 0 while intentionally keeping p->dl.deadline and p->dl.period_start.

The !p->dl.dl_runtime check then fires and zeroes both fields. If the task re-enters SCHED_DEADLINE before its next period, dl_check_constrained_dl() skips throttling and starts a fresh period immediately, bypassing bandwidth confinement.

Checking !p->dl.dl_runtime before task_non_contending() (or using else if) would avoid clobbering the preserved state.

[ ... ]

Quoted 6 lines
kernel/sched/deadline.c +1 -0
@@ -5224,12 +5231,16 @@ static void __dl_clear_params(struct sched_dl_entity *dl_se)
  */
 static void dl_release_params(struct sched_dl_entity *dl_se)
 {
+	u64 period_start = dl_se->period_start;
 	u64 deadline = dl_se->deadline;

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

Quoted 10 lines
kernel/sched/deadline.c +4 -1
 	bool constrained = !dl_is_implicit(dl_se);
 
 	__dl_clear_params(dl_se);
-	if (constrained)
+	if (constrained) {
+		/* Keep the start of the period with its deadline. */
+		dl_se->period_start = period_start;
 		dl_se->deadline = deadline;
+	}
 }

[Severity: Medium]
Is dl_release_params() safe if it runs twice for a departing constrained-deadline task?

When inactive_task_timer() has already fired on another CPU and is waiting for task_rq_lock(p), hrtimer_active() is still true. If the task switches out of SCHED_DEADLINE concurrently, task_non_contending() calls dl_release_params() first, and inactive_task_timer() calls it again:

CPU0 CPU1
inactive_task_timer()
task_rq_lock(p) (spins)
switched_from_dl()
task_non_contending()

    hrtimer_active() == true
    dl_release_params()
      clears dl_deadline/period
      keeps deadline/period_start

rq unlock
(acquires rq lock) dl_release_params()
dl_is_implicit() == true clears deadline/period_start <-- wiped

On the second call, dl_deadline and dl_period are both 0, so dl_is_implicit() returns true and __dl_clear_params() wipes the preserved deadline and period_start. A task that re-enters SCHED_DEADLINE before its next period then skips throttling in dl_check_constrained_dl().

Returning early in dl_release_params() when !dl_se->dl_deadline (or guarding the call in inactive_task_timer() on dl_se->dl_runtime) would prevent the second call from clearing the preserved state.

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

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

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

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

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

selftests/sched: Test parameter changes in deadline_bw_test

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

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

[ ... ]

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

[ ... ]

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

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

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

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

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

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

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

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

[ ... ]

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

[ ... ]

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

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

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

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

[ ... ]

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

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

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

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

[ ... ]

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

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

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

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

[ ... ]

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

[ ... ]

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

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

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

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

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

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

[ ... ]

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

[ ... ]

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

[ ... ]

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

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

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

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

[ ... ]

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

[ ... ]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[ ... ]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Quoted 4 lines

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

[ ... ]

Quoted 3 lines

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

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

[ ... ]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

[ ... ]

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

[ ... ]

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

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

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

parent W (race_w)

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

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

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

[ ... ]

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

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

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

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

[ ... ]

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

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

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

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

[ ... ]

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

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

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

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

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

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

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

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

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

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

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

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

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

[ ... ]

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

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

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

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

[ ... ]

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

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

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

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

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

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

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

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

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

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

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

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

[ ... ]

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

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

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

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

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

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

[ ... ]

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

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

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

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

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

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

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

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

[ ... ]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Re: [PATCH v14 01/39] sched/deadline: Hold a reference on the deadline donor of a boosted task

In reply to Mathieu Desnoyers
Quoted 51 lines · Mathieu Desnoyers
kernel/sched/sched.h +51 -0
+#ifdef CONFIG_RT_MUTEXES
+/*
+ * Make @pi_se the deadline donor of @dl_se. The caller holds a reference
+ * on the task of @pi_se, unless @pi_se is @dl_se. Put the reference on
+ * the old donor.
+ */
+static inline void dl_replace_donor(struct sched_dl_entity *dl_se,
+				    struct sched_dl_entity *pi_se)
+{
+	struct sched_dl_entity *old = dl_se->pi_se;
+
+	WRITE_ONCE(dl_se->pi_se, pi_se);
+	if (old != dl_se)
+		put_task_struct(container_of(old, struct task_struct, dl));
+}
+
+/* Reads of the donor of a waiter before the lookup falls back. */
+#define DL_DONOR_TRIES	8
+
+/*
+ * Make the deadline donor of the waiter @pi_task the donor of @dl_se. A
+ * boosted entity holds a reference on the task of its donor. The donor
+ * is the deadline task at the head of the chain. It can stop waiting
+ * and exit before the chain walk reaches @dl_se: that walk can be
+ * preempted.
+ *
+ * The donor of @pi_task is read without the locks of @pi_task. Another
+ * CPU can change it meanwhile, and put the last reference on the old
+ * donor. That CPU stores the new donor first: read it again then. The
+ * old task_struct stays readable while the rq lock is held:
+ * put_task_struct() frees it through call_rcu(), and the rq lock holds
+ * off the grace period.
+ *
+ * Each failed tryget_task_struct() means that another CPU stored a newer
+ * donor. This holds as long as every writer of pi_se holds a reference
+ * on the new donor. A writer that breaks this rule could leave a dead
+ * donor in pi_se, and every read would fail on it. So stop after
+ * DL_DONOR_TRIES reads, rather than spin forever with interrupts off.
+ * Warn, and fall back to @pi_task itself. It waits on a lock, so it
+ * cannot exit. If it has no parameters of its own,
+ * replenish_dl_entity() handles it as a donor that left the class.
+ *
+ * The caller holds the rq lock and the pi_lock of the task of @dl_se.
+ */
+static inline void dl_set_donor(struct sched_dl_entity *dl_se,
+				struct task_struct *pi_task)
+{
+	struct sched_dl_entity *pi_se;
+	int tries;
+
+	for (tries = 0; tries < DL_DONOR_TRIES; tries++) {

kernel/sched/sched.h extern int sched_dl_global_validate(void); · line 419

Quoted 10 lines
kernel/sched/sched.h +10 -0
+		pi_se = READ_ONCE(pi_task->dl.pi_se);
+		if (pi_se == dl_se->pi_se)
+			return;
+		if (pi_se == dl_se ||
+		    tryget_task_struct(container_of(pi_se, struct task_struct, dl)))
+			goto set;
+		/* Pairs with the ordering of refcount_dec_and_test(). */
+		smp_rmb();
+	}
+	WARN_ON_ONCE(1);

*groan*, so it feels like this WARN is something that could be constructed to trigger, which would be bad.

All this takes is for a high frequency pthread_cancel() or somesuch, no? Create a ton of high prio tasks, get them involved in a boost chain and cancel them.

Or am I missing soemthing?

Quoted 15 lines
kernel/sched/sched.h +15 -0
+	pi_se = &pi_task->dl;
+	if (pi_se == dl_se->pi_se)
+		return;
+	if (pi_se != dl_se)
+		get_task_struct(pi_task);
+set:
+	dl_replace_donor(dl_se, pi_se);
+}
+
+/* Make @dl_se its own donor. The caller holds the rq lock of its task. */
+static inline void dl_clear_donor(struct sched_dl_entity *dl_se)
+{
+	dl_replace_donor(dl_se, dl_se);
+}
+#endif
#4 lore raw

Re: [PATCH v14 01/39] sched/deadline: Hold a reference on the deadline donor of a boosted task

Quoted 17 lines · Peter Zijlstra

kernel/sched/sched.h extern int sched_dl_global_validate(void); · line 419

Quoted 11 lines · Mathieu Desnoyers
kernel/sched/sched.h +11 -0
+	for (tries = 0; tries < DL_DONOR_TRIES; tries++) {
+		pi_se = READ_ONCE(pi_task->dl.pi_se);
+		if (pi_se == dl_se->pi_se)
+			return;
+		if (pi_se == dl_se ||
+		    tryget_task_struct(container_of(pi_se, struct task_struct, dl)))
+			goto set;
+		/* Pairs with the ordering of refcount_dec_and_test(). */
+		smp_rmb();
+	}
+	WARN_ON_ONCE(1);

*groan*, so it feels like this WARN is something that could be constructed to trigger, which would be bad.

Quoted 5 lines

All this takes is for a high frequency pthread_cancel() or somesuch, no? Create a ton of high prio tasks, get them involved in a boost chain and cancel them.

Or am I missing soemthing?

No, you are right. Correct writers can trigger it. Each failed tryget_task_struct() is a donor that a writer replaced, and that then exited. If enough donors join the chain and exit quickly, 8 reads in a row can fail. A slow reader makes it easier, for example a preempted vCPU.

The fallback itself is safe. The top waiter is blocked, so it cannot exit. The boosted task then runs on the parameters of the top waiter. They are not those of the head of the chain, but they come from a live task.

The planned next version will drop the WARN_ON_ONCE() and keep the bound of 8 reads. The comment and the changelog will describe the fallback as a rare but normal path.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
#5 lore raw

Re: [PATCH v14 01/39] sched/deadline: Hold a reference on the deadline donor of a boosted task

Quoted 1 line · Mathieu Desnoyers

The planned next version will drop the WARN_ON_ONCE() and keep the

be aware that all printks with the RQ held can be deadly if the console is not nbcon.

Quoted 3 lines

Thanks,

Mathieu

Sebastian

#6 lore raw

Re: [PATCH v14 01/39] sched/deadline: Hold a reference on the deadline donor of a boosted task

In reply to Mathieu Desnoyers
Quoted 4 lines · Mathieu Desnoyers

The fallback itself is safe. The top waiter is blocked, so it cannot exit. The boosted task then runs on the parameters of the top waiter. They are not those of the head of the chain, but they come from a live task.

This was incomplete. In a chain, the top waiter is often a boosted SCHED_OTHER task, with no deadline parameters of its own. After the fallback, replenish_dl_entity() finds no parameters in the donor. It gives the owner a deadline of now and no runtime, at every tick. The owner then runs ahead of every deadline task on its CPU.

The same state happens without the fallback. When the donor of a blocked, boosted task changes, the owners below it keep the old donor. The blocked task keeps prio -1, and its dl.deadline does not change while it sleeps. So rt_mutex_adjust_prio_chain() sees no change at step [3], and stops before the owners below it.

One CPU. O and M are SCHED_OTHER. A (10ms/100ms) and B (20ms/200ms) are SCHED_DEADLINE. L1 and L2 are PI futexes. A takes L1 with a timeout:

O M A B

locks L2
spins locks L1
blocks on L2
blocks on L1
M, O: donor A
blocks on L1
top waiter: A
times out on L1
M: donor B
O: still donor A
exits
0-lag time:
parameters cleared
replenish_dl_entity(O):
A's parameters are 0
deadline = now

The "no parameters" branch comes from "sched/deadline: Do not replenish a boost from cleared parameters", in the first series. Its changelog expects the deboost to come "soon enough". Here no walk reaches O before it releases L2.

I reproduced this on v14, in a VM with one CPU, with proxy execution on and off. A third deadline task runs a 3ms job every 50ms, with a 50ms deadline. From A's 0-lag time until O releases L2, two jobs out of three miss their deadline. In the control run, A stays alive after its timeout, and no job misses its deadline. A debug printk confirmed the donors of M and O, and the refills of O.

The walk stops at M upstream too: the series does not change rtmutex.c. Upstream, O would read the freed task_struct of A. This is from reading: I did not run upstream. This patch fixes that, but its changelog is wrong in three places:
- "for a while": the owner keeps the exited donor until it releases the lock.
- "The boost is then only less accurate": not when the top waiter has no parameters (see above).
- "it needs a walk preempted at the right step": the scenario above needs none.

Neither v14 nor dropping the WARN, as planned in my previous mail, fixes this.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com