mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters
@ 2026-12-01  6:27 Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 1/6] locking/rwsem: Track held rwsems per task Peng Huang
                   ` (5 more replies)
  0 siblings, 6 replies; 9+ messages in thread
From: Peng Huang @ 2026-12-01  6:27 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot
  Cc: Waiman Long, Dietmar Eggemann, Steven Rostedt, Ben Segall,
	Mel Gorman, Valentin Schneider, K Prateek Nayak, John Stultz,
	Suren Baghdasaryan, linux-kernel, linux-mm, Peng Huang,
	Sebastian Andrzej Siewior, Clark Williams, linux-rt-devel

Hi,

High-priority threads (e.g. UI/render) can stall for tens to hundreds
of milliseconds on shared rw_semaphores like mmap_lock or i_rwsem when
preempted low-priority or SCHED_IDLE readers block a writer.  Outside
PREEMPT_RT, rwsems have no PI, Proxy Execution covers only mutexes,
and read-owners are anonymous.  This hits both servers (/proc/pid/
cmdline, background MADV_COLD) and phones (nice -10 UI vs. background
MADV_PAGEOUT on small cores, where we found it).

This RFC raises the fair load weight of contended rwsem holders:
- Patches 1-2: per-task tracking of up to 4 held rwsems (no atomics);
  btrfs untracks i_rwsem before cross-task io_uring completion.
- Patch 3: pack top waiter priority into sem->count bits 3..8 (no
  struct rw_semaphore growth).
- Patches 4-5: apply boost in set_load_weight() (p->prio and PI
  untouched); re-check queued holders on enqueue, preemption, and
  tick; drop on unlock.
- Patch 6: KUnit suite (16 cases, 20 tests).

Opt-in via CONFIG_RWSEM_SCHED_BOOST; disable at boot with
rwsem_sched_boost=0.

Questions for this RFC
----------------------
- Is per-task tracking + weight boost acceptable for readers, or
  should this wait for Proxy Execution to cover rwsems?
- Track readers and writers, or readers only (leaving writers to PE)?
- Raw pointer slots (+56 B/task, explicit untrack) or a hash table?
- Reweight via set_load_weight() (stays in cgroup share, moves PELT)
  or a floor on flattened EEVDF weight (crosses cgroups, skips PELT)?

Known limits
------------
- Weight is not PI; only runnable holders benefit (not I/O-blocked).
  Queued holders wait up to one tick; at most 4 rwsems/task tracked.
- Waiter priority is sampled on queue (so rwsem-to-rwsem propagates
  when a boosted holder queues, but not across mutexes or futexes);
  concurrent readers share the boost.
- Under FAIR_GROUP_SCHED, boost stays within the holder's cgroup
  share; a boosted SCHED_IDLE holder still yields to non-idle wakeups.
- Under Proxy Execution, a fair task running for a non-fair donor is
  linked only on its next enqueue or preemption.

Results (mean high-priority waiter latency)
-------------------------------------------
- KUnit (UML, nice +19 reader + 4 nice 0 hogs, nice -10 writer):
  1813 -> 50 ms (-97.2%, median of 3; control 1.77-1.81 s).
- QEMU x86_64 -smp 4 (TCG), mmap_lock, same setup (10 runs):
  445.8 -> 8.7 ms within one image (-98.1%, max 14.9 ms, 0/200 > 16 ms;
  BASE 394.4 ms, TCG shifts up to 20% across images).
- ARM64 phone (older 6.18 backport), mmap_lock, nice -10 vs. 7 hogs:
  46.95 -> 8.89 ms (-81.1%) unpinned, 229.5 -> 19.4 ms (-91.5%) mid.

Costs and non-results
---------------------
- UML uncontended fastpath (boost=0 -> 1, median of 3): read 16.9 ->
  20.2, write 17.1 -> 19.8, nested read 16.9 -> 21.8 ns/op; boosted
  holder cycling an unrelated rwsem: 28.5 ns/op.
- Tick scan: walks up to 16 queued holders per tick under rq->lock
  (round-robin, up to 4 sem->count reads each); not measured alone.
- Waiter prio rescan: O(1) when waiters share priority; losing a sole
  top waiter rescans remaining waiters under wait_lock (O(waiters)).
- QEMU (boost=0 -> 1, 10 runs): madvise +2.4%, mprotect +1.4% (+0.4%
  median); equal-priority contention -4.3% mean, -5.6% median
  (196-240 ms on vs. 195-268 ms off).
- ARM64 (same backport): madvise -2.2%, mprotect +0.2%; boot-time
  hackbench +6.6% and pipe +0.2% (settled -8.7% and -0.7%);
  equal-priority contention -10.6% mid-pinned, -2.8% mean / +12.1%
  median unpinned.
- Browser warm launch from zRAM (same backport, 22 vs. 23 runs):
  +2.4% (p=0.45); holders spent 91-96% of inversion in D state (I/O).
- Reader count loses 1 bit (22 bits on 32-bit, > PID_MAX_LIMIT).
  Memory: +56 B/task_struct, +16 B/rq.

Changes in v2
-------------
- Boost fair load weight only (leave p->prio, static_prio, PI alone).
- Pack waiter prio into sem->count (32 B rwsem); lockless drop check.
- Move all hooks into fair.c; drop idle-balance pull; handle Proxy
  Execution donors and delayed dequeue.
- Split into 6 patches, opt-in Kconfig, fixed 4 slots, 16 KUnit cases.

Based on tip/sched/core (74ce3843347b).
v1: https://lore.kernel.org/all/20261119224954.196990-1-penghuang@google.com/

Tool disclosure (Documentation/process/generated-content.rst): an
LLM-based coding assistant (Gemini, via Google-internal tooling) helped
draft parts of the code, changelogs, KUnit tests, and this letter, and
ran review, refactoring, and test passes.  I reviewed and edited all of
it and take full responsibility for the series.

Peng Huang (6):
  locking/rwsem: Track held rwsems per task
  btrfs: untrack i_rwsem before io_uring encoded read completion
  locking/rwsem: Publish the top waiter priority
  sched: Apply rwsem holder boost to the fair load weight
  sched/fair: Boost rwsem holders with contended high-priority waiters
  locking/rwsem: Add KUnit tests for scheduler priority boost

 .../admin-guide/kernel-parameters.txt         |    5 +
 fs/btrfs/ioctl.c                              |    7 +
 include/linux/rwsem.h                         |   46 +
 include/linux/sched.h                         |   34 +
 init/init_task.c                              |    6 +
 kernel/Kconfig.locks                          |   15 +
 kernel/locking/Makefile                       |    1 +
 kernel/locking/rwsem.c                        |  387 ++++-
 kernel/locking/rwsem_sched_boost_test.c       | 1468 +++++++++++++++++
 kernel/sched/core.c                           |   92 +-
 kernel/sched/fair.c                           |  326 ++++
 kernel/sched/sched.h                          |   59 +
 lib/Kconfig.debug                             |   17 +
 13 files changed, 2442 insertions(+), 21 deletions(-)
 create mode 100644 kernel/locking/rwsem_sched_boost_test.c


base-commit: 74ce3843347b0fe192e9bf29f46e1a266515defa
-- 
2.56.1.839.g22a8290db9-goog


^ permalink raw reply	[flat|nested] 9+ messages in thread

* [RFC PATCH v2 1/6] locking/rwsem: Track held rwsems per task
  2026-12-01  6:27 [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters Peng Huang
@ 2026-12-01  6:27 ` Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 2/6] btrfs: untrack i_rwsem before io_uring encoded read completion Peng Huang
                   ` (4 subsequent siblings)
  5 siblings, 0 replies; 9+ messages in thread
From: Peng Huang @ 2026-12-01  6:27 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot
  Cc: Waiman Long, Dietmar Eggemann, Steven Rostedt, Ben Segall,
	Mel Gorman, Valentin Schneider, K Prateek Nayak, John Stultz,
	Suren Baghdasaryan, linux-kernel, linux-mm, Peng Huang,
	Jonathan Corbet, Shuah Khan, Randy Dunlap,
	Sebastian Andrzej Siewior, Clark Williams, linux-doc,
	linux-rt-devel

An rw_semaphore does not track its readers: sem->owner keeps at most
the last reader as a hint, because tracking all readers in the lock
was considered too expensive.  Nothing can find the tasks holding an
rwsem for read.

Track the other way round: record up to RWSEM_SCHED_BOOST_SLOTS (4)
held rwsems per task in struct rwsem_sched_boost so later patches can
boost preempted holders.

Only current writes held[] and nr_held, adding no atomics to the
fastpath.  Trylocks skip IRQ and irqs_disabled() callers (e.g. BPF
helpers that defer unlock to irq_work).  A blocking reader takes a
slot before queueing, because rwsem_mark_wake() grants the lock before
the reader runs; an interrupted wait drops it under wait_lock.  Slots
are cleared before sem->count is released, so they never outlive their
lock.

down_read_non_owner() drops its slot immediately, and callers handing
a held rwsem to another task must call rwsem_boost_untrack() first.
A v7.4-rc5 audit found one plain rwsem released cross-task (btrfs
io_uring encoded reads, handled next); all *_non_owner() releases
already pair with untracked acquisitions.

Add CONFIG_RWSEM_SCHED_BOOST (default n) and rwsem_sched_boost=.

Signed-off-by: Peng Huang <penghuang@google.com>
---
 .../admin-guide/kernel-parameters.txt         |   5 +
 include/linux/rwsem.h                         |  14 ++
 include/linux/sched.h                         |  25 +++
 kernel/Kconfig.locks                          |  15 ++
 kernel/locking/rwsem.c                        | 179 ++++++++++++++++--
 5 files changed, 222 insertions(+), 16 deletions(-)

diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index 176648941aec..2c5207dd9c53 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -6778,6 +6778,11 @@ Kernel parameters
 
 	rw		[KNL] Mount root device read-write on boot
 
+	rwsem_sched_boost=
+			[KNL] Enable or disable rwsem scheduler priority
+			boosting when CONFIG_RWSEM_SCHED_BOOST=y.
+			Defaults to 1 (enabled). Format: <bool>
+
 	S		[KNL] Run init in single mode
 
 	s390_iommu=	[HW,S390]
diff --git a/include/linux/rwsem.h b/include/linux/rwsem.h
index 6a1a7bae5f81..2df33131bb5f 100644
--- a/include/linux/rwsem.h
+++ b/include/linux/rwsem.h
@@ -327,8 +327,22 @@ extern void up_read_non_owner(struct rw_semaphore *sem) __releases_shared(sem);
 # define down_write_nest_lock(sem, nest_lock)	down_write(sem)
 # define down_write_nested(sem, subclass)	down_write(sem)
 # define down_write_killable_nested(sem, subclass)	down_write_killable(sem)
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+void down_read_non_owner(struct rw_semaphore *sem) __acquires_shared(sem);
+void up_read_non_owner(struct rw_semaphore *sem) __releases_shared(sem);
+#else
 # define down_read_non_owner(sem)		down_read(sem)
 # define up_read_non_owner(sem)			up_read(sem)
 #endif
+#endif
+
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+void rwsem_boost_untrack(struct rw_semaphore *sem);
+bool rwsem_boost_set(bool enable);
+#else
+static inline void rwsem_boost_untrack(struct rw_semaphore *sem)
+{
+}
+#endif
 
 #endif /* _LINUX_RWSEM_H */
diff --git a/include/linux/sched.h b/include/linux/sched.h
index 7cd8df8f463c..a98be7c4537d 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -78,6 +78,7 @@ struct rcu_node;
 struct reclaim_state;
 struct root_domain;
 struct rq;
+struct rw_semaphore;
 struct sched_attr;
 struct sched_dl_entity;
 struct seq_file;
@@ -833,6 +834,26 @@ struct task_ipi_mask {
 struct task_ipi_mask { };
 #endif
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+#define RWSEM_SCHED_BOOST_SLOTS		4
+
+/**
+ * struct rwsem_sched_boost - per-task rw_semaphore boost state
+ * @nr_held:	number of non-NULL entries in @held
+ * @held:	rw_semaphores held, one slot per tracked acquisition
+ *
+ * Only the task itself writes @nr_held and @held, so the lock
+ * fastpaths need no atomics.  A slot is filled before the rwsem can
+ * be granted (a blocking reader fills it before it queues) and cleared
+ * before the rwsem is released or the wait is abandoned, so a
+ * non-NULL slot always names an rwsem the task holds or waits for.
+ */
+struct rwsem_sched_boost {
+	u8				nr_held;
+	struct rw_semaphore		*held[RWSEM_SCHED_BOOST_SLOTS];
+};
+#endif
+
 struct task_struct {
 #ifdef CONFIG_THREAD_INFO_IN_TASK
 	/*
@@ -927,6 +948,10 @@ struct task_struct {
 	struct uclamp_se		uclamp[UCLAMP_CNT];
 #endif
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+	struct rwsem_sched_boost	rwsem_boost;
+#endif
+
 	struct sched_statistics         stats;
 
 #ifdef CONFIG_PREEMPT_NOTIFIERS
diff --git a/kernel/Kconfig.locks b/kernel/Kconfig.locks
index 1c6423aafcd4..8e67fe0b6f8d 100644
--- a/kernel/Kconfig.locks
+++ b/kernel/Kconfig.locks
@@ -279,3 +279,18 @@ config ARCH_HAS_MMIOWB
 config MMIOWB
 	def_bool y if ARCH_HAS_MMIOWB
 	depends on SMP
+
+config RWSEM_SCHED_BOOST
+	bool "Scheduler priority boost for contended rw_semaphores"
+	depends on !PREEMPT_RT
+	help
+	  Track held rw_semaphores per task and temporarily raise the load
+	  weight of fair holders that block higher-priority waiters, to
+	  mitigate reader and writer priority inversion.
+
+	  Every rwsem lock and unlock records or clears a per-task slot
+	  (no atomic operations), task_struct grows by 56 bytes and each
+	  runqueue by 16.  Boot with rwsem_sched_boost=0 to turn the
+	  tracking off.
+
+	  If unsure, say N.
diff --git a/kernel/locking/rwsem.c b/kernel/locking/rwsem.c
index b9c180ac1eee..798a8db7636c 100644
--- a/kernel/locking/rwsem.c
+++ b/kernel/locking/rwsem.c
@@ -28,8 +28,131 @@
 #include <linux/rwsem.h>
 #include <linux/atomic.h>
 #include <linux/hung_task.h>
+#include <linux/jump_label.h>
 #include <trace/events/lock.h>
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+static DEFINE_STATIC_KEY_TRUE(rwsem_boost_key);
+
+/**
+ * rwsem_boost_set - Enable or disable rwsem holder boosting
+ * @enable: track held rwsems and publish waiter priorities if true
+ *
+ * Return: the previous state.
+ */
+bool rwsem_boost_set(bool enable)
+{
+	bool was_enabled = static_key_enabled(&rwsem_boost_key);
+
+	if (enable)
+		static_branch_enable(&rwsem_boost_key);
+	else
+		static_branch_disable(&rwsem_boost_key);
+	return was_enabled;
+}
+
+static int __init rwsem_boost_cmdline(char *str)
+{
+	bool enable;
+
+	if (kstrtobool(str, &enable) != 0)
+		return 0;
+	rwsem_boost_set(enable);
+	return 1;
+}
+__setup("rwsem_sched_boost=", rwsem_boost_cmdline);
+
+/*
+ * Record @sem in a free held[] slot so the scheduler can find the
+ * holders of a contended rwsem.  Blocking acquisitions call this
+ * directly: might_sleep() guarantees task context.
+ */
+static inline void rwsem_boost_track(struct rw_semaphore *sem)
+{
+	struct rwsem_sched_boost *b = &current->rwsem_boost;
+	int i;
+
+	if (!static_branch_likely(&rwsem_boost_key))
+		return;
+
+	/* rwsems do not recurse; a recursive trylock takes a slot. */
+	for (i = 0; i < RWSEM_SCHED_BOOST_SLOTS; i++) {
+		if (!b->held[i]) {
+			WRITE_ONCE(b->held[i], sem);
+			WRITE_ONCE(b->nr_held, b->nr_held + 1);
+			return;
+		}
+	}
+}
+
+/*
+ * Trylocks can run in IRQ context or with IRQs disabled, e.g. BPF
+ * helpers that defer the unlock to irq_work and release the lock
+ * with up_read_non_owner().  Leave those untracked.
+ */
+static inline void rwsem_boost_track_trylock(struct rw_semaphore *sem)
+{
+	if (unlikely(!in_task()))
+		return;
+	if (unlikely(irqs_disabled()))
+		return;
+	rwsem_boost_track(sem);
+}
+
+/*
+ * Clear @sem from held[] before sem->count is released, so that once
+ * another task can acquire or free @sem, scheduler inspection no
+ * longer finds it.  Unlike tracking, ignore rwsem_boost_key and
+ * irqs_disabled() so no slot outlives its lock; an acquire that was
+ * not tracked can only end tracking early (losing boost).
+ */
+static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
+{
+	struct rwsem_sched_boost *b = &current->rwsem_boost;
+	u8 nr = b->nr_held;
+	int i;
+
+	if (nr == 0)
+		return;
+	/* IRQ/softirq unlocks pair with untracked trylocks. */
+	if (unlikely(!in_task()))
+		return;
+
+	for (i = 0; i < RWSEM_SCHED_BOOST_SLOTS; i++) {
+		if (b->held[i] == sem) {
+			WRITE_ONCE(b->held[i], NULL);
+			WRITE_ONCE(b->nr_held, nr - 1);
+			return;
+		}
+	}
+}
+
+/**
+ * rwsem_boost_untrack - Stop tracking @sem as held by current
+ * @sem: rwsem that current holds
+ *
+ * Call before another context can release @sem, e.g. an io_uring
+ * completion that runs in a different task.  Task context only.
+ */
+void rwsem_boost_untrack(struct rw_semaphore *sem)
+{
+	__rwsem_boost_untrack(sem);
+}
+EXPORT_SYMBOL_GPL(rwsem_boost_untrack);
+#else
+static inline void rwsem_boost_track(struct rw_semaphore *sem)
+{
+}
+
+static inline void rwsem_boost_track_trylock(struct rw_semaphore *sem)
+{
+}
+
+static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
+{
+}
+#endif
+
 #ifndef CONFIG_PREEMPT_RT
 #include "lock_events.h"
 
@@ -255,6 +378,7 @@ static inline bool rwsem_read_trylock(struct rw_semaphore *sem, long *cntp)
 
 	if (!(*cntp & RWSEM_READ_FAILED_MASK)) {
 		rwsem_set_reader_owned(sem);
+		rwsem_boost_track(sem);
 		return true;
 	}
 
@@ -1021,6 +1145,12 @@ rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int stat
 	struct rwsem_waiter waiter, *first;
 	DEFINE_WAKE_Q(wake_q);
 
+	/*
+	 * Track @sem before queueing, as rwsem_mark_wake() grants the
+	 * lock to queued readers before they run; out_nolock untracks.
+	 */
+	rwsem_boost_track(sem);
+
 	/*
 	 * To prevent a constant stream of readers from starving a sleeping
 	 * writer, don't attempt optimistic lock stealing if the lock is
@@ -1125,6 +1255,8 @@ rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int stat
 	return sem;
 
 out_nolock:
+	/* Under wait_lock: drop the slot before @sem may be freed. */
+	__rwsem_boost_untrack(sem);
 	rwsem_del_wake_waiter(sem, &waiter, &wake_q);
 	__set_current_state(TASK_RUNNING);
 	lockevent_inc(rwsem_rlock_fail);
@@ -1327,6 +1459,7 @@ static inline int __down_read_trylock(struct rw_semaphore *sem)
 		if (atomic_long_try_cmpxchg_acquire(&sem->count, &tmp,
 						    tmp + RWSEM_READER_BIAS)) {
 			rwsem_set_reader_owned(sem);
+			rwsem_boost_track_trylock(sem);
 			ret = 1;
 			break;
 		}
@@ -1344,9 +1477,14 @@ static __always_inline int __down_write_common(struct rw_semaphore *sem, int sta
 
 	preempt_disable();
 	if (unlikely(!rwsem_write_trylock(sem))) {
-		if (IS_ERR(rwsem_down_write_slowpath(sem, state)))
+		sem = rwsem_down_write_slowpath(sem, state);
+		if (IS_ERR(sem)) {
 			ret = -EINTR;
+			goto out;
+		}
 	}
+	rwsem_boost_track(sem);
+out:
 	preempt_enable();
 	return ret;
 }
@@ -1368,6 +1506,8 @@ static inline int __down_write_trylock(struct rw_semaphore *sem)
 	preempt_disable();
 	DEBUG_RWSEMS_WARN_ON(sem->magic != sem, sem);
 	ret = rwsem_write_trylock(sem);
+	if (ret == 1)
+		rwsem_boost_track_trylock(sem);
 	preempt_enable();
 
 	return ret;
@@ -1384,6 +1524,7 @@ static inline void __up_read(struct rw_semaphore *sem)
 	DEBUG_RWSEMS_WARN_ON(!is_rwsem_reader_owned(sem), sem);
 
 	preempt_disable();
+	__rwsem_boost_untrack(sem);
 	rwsem_clear_reader_owned(sem);
 	tmp = atomic_long_add_return_release(-RWSEM_READER_BIAS, &sem->count);
 	DEBUG_RWSEMS_WARN_ON(tmp < 0, sem);
@@ -1413,6 +1554,7 @@ static inline void __up_write(struct rw_semaphore *sem)
 			    !rwsem_test_oflags(sem, RWSEM_NONSPINNABLE), sem);
 
 	preempt_disable();
+	__rwsem_boost_untrack(sem);
 	rwsem_clear_owner(sem);
 	tmp = atomic_long_fetch_add_release(-RWSEM_WRITER_LOCKED, &sem->count);
 	if (unlikely(tmp & RWSEM_FLAG_WAITERS)) {
@@ -1735,21 +1877,6 @@ void _down_write_nest_lock(struct rw_semaphore *sem, struct lockdep_map *nest)
 }
 EXPORT_SYMBOL(_down_write_nest_lock);
 
-void down_read_non_owner(struct rw_semaphore *sem)
-	__no_context_analysis
-{
-	might_sleep();
-	__down_read(sem);
-	/*
-	 * The owner value for a reader-owned lock is mostly for debugging
-	 * purpose only and is not critical to the correct functioning of
-	 * rwsem. So it is perfectly fine to set it in a preempt-enabled
-	 * context here.
-	 */
-	__rwsem_set_reader_owned(sem, NULL);
-}
-EXPORT_SYMBOL(down_read_non_owner);
-
 void down_write_nested(struct rw_semaphore *sem, int subclass)
 	__no_context_analysis
 {
@@ -1775,6 +1902,26 @@ int __sched down_write_killable_nested(struct rw_semaphore *sem, int subclass)
 }
 EXPORT_SYMBOL(down_write_killable_nested);
 
+#endif
+
+#if defined(CONFIG_DEBUG_LOCK_ALLOC) || defined(CONFIG_RWSEM_SCHED_BOOST)
+void down_read_non_owner(struct rw_semaphore *sem)
+	__no_context_analysis
+{
+	might_sleep();
+	__down_read(sem);
+	/* Another context releases it: leave no slot behind. */
+	rwsem_boost_untrack(sem);
+	/*
+	 * The owner value for a reader-owned lock is mostly for debugging
+	 * purpose only and is not critical to the correct functioning of
+	 * rwsem. So it is perfectly fine to set it in a preempt-enabled
+	 * context here.
+	 */
+	__rwsem_set_reader_owned(sem, NULL);
+}
+EXPORT_SYMBOL(down_read_non_owner);
+
 void up_read_non_owner(struct rw_semaphore *sem)
 	__no_context_analysis
 {
-- 
2.56.1.839.g22a8290db9-goog


^ permalink raw reply	[flat|nested] 9+ messages in thread

* [RFC PATCH v2 2/6] btrfs: untrack i_rwsem before io_uring encoded read completion
  2026-12-01  6:27 [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 1/6] locking/rwsem: Track held rwsems per task Peng Huang
@ 2026-12-01  6:27 ` Peng Huang
  2026-12-01  8:40   ` Christoph Hellwig
  2026-12-01  6:27 ` [RFC PATCH v2 3/6] locking/rwsem: Publish the top waiter priority Peng Huang
                   ` (3 subsequent siblings)
  5 siblings, 1 reply; 9+ messages in thread
From: Peng Huang @ 2026-12-01  6:27 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot
  Cc: Waiman Long, Dietmar Eggemann, Steven Rostedt, Ben Segall,
	Mel Gorman, Valentin Schneider, K Prateek Nayak, John Stultz,
	Suren Baghdasaryan, linux-kernel, linux-mm, Peng Huang,
	David Sterba, Chris Mason, linux-btrfs

btrfs_uring_encoded_read() takes the inode lock shared through
btrfs_encoded_read() in the submitting task, but
btrfs_uring_read_finished() may release it from another task once the
reads complete.  With CONFIG_RWSEM_SCHED_BOOST the submitter's
held-lock slot would then outlive the lock.

Call rwsem_boost_untrack() in btrfs_uring_read_extent() before
submitting the reads.  If submission fails, the caller's own unlock
simply finds no slot.

Signed-off-by: Peng Huang <penghuang@google.com>
---
 fs/btrfs/ioctl.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c
index 6ba883db107b..073450a6df95 100644
--- a/fs/btrfs/ioctl.c
+++ b/fs/btrfs/ioctl.c
@@ -4725,6 +4725,13 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter,
 	priv->lockend = lockend;
 	priv->err = 0;
 
+	/*
+	 * Once the reads are queued, btrfs_uring_read_finished() may
+	 * unlock i_rwsem from another task, so stop tracking it as held
+	 * by this one.  On error the caller's unlock finds no record.
+	 */
+	rwsem_boost_untrack(&inode->vfs_inode.i_rwsem);
+
 	ret = btrfs_encoded_read_regular_fill_pages(inode, disk_bytenr,
 						    disk_io_size, pages, priv);
 	if (ret && ret != -EIOCBQUEUED)
-- 
2.56.1.839.g22a8290db9-goog


^ permalink raw reply	[flat|nested] 9+ messages in thread

* [RFC PATCH v2 3/6] locking/rwsem: Publish the top waiter priority
  2026-12-01  6:27 [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 1/6] locking/rwsem: Track held rwsems per task Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 2/6] btrfs: untrack i_rwsem before io_uring encoded read completion Peng Huang
@ 2026-12-01  6:27 ` Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 4/6] sched: Apply rwsem holder boost to the fair load weight Peng Huang
                   ` (2 subsequent siblings)
  5 siblings, 0 replies; 9+ messages in thread
From: Peng Huang @ 2026-12-01  6:27 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot
  Cc: Waiman Long, Dietmar Eggemann, Steven Rostedt, Ben Segall,
	Mel Gorman, Valentin Schneider, K Prateek Nayak, John Stultz,
	Suren Baghdasaryan, linux-kernel, linux-mm, Peng Huang

Holders need to know how urgent their waiters are without walking the
wait list.  Pack the top waiter priority into sem->count bits 3..8
(encoded as MAX_PRIO - prio, 0 = no demand) and expose
rwsem_top_waiter_prio(), shifting the reader count up by one bit so
struct rw_semaphore stays 32 bytes (54 reader bits on 64-bit, 22 on
32-bit).

Each waiter samples its priority before taking wait_lock: RT/DL
waiters cap at MAX_RT_PRIO (nice -20) and SCHED_IDLE waiters ask for
no boost.  The field is maintained under wait_lock alongside existing
sem->count updates; only losing a top waiter triggers a rescan, which
stops at the first remaining match (O(1) for equal-priority waiters).
Nothing reads it yet.

Signed-off-by: Peng Huang <penghuang@google.com>
---
 include/linux/rwsem.h  |  31 ++++++++
 kernel/locking/rwsem.c | 177 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 205 insertions(+), 3 deletions(-)

diff --git a/include/linux/rwsem.h b/include/linux/rwsem.h
index 2df33131bb5f..d8a49170efd2 100644
--- a/include/linux/rwsem.h
+++ b/include/linux/rwsem.h
@@ -16,6 +16,9 @@
 #include <linux/atomic.h>
 #include <linux/err.h>
 #include <linux/cleanup.h>
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+#include <linux/sched/prio.h>
+#endif
 
 #ifdef CONFIG_DEBUG_LOCK_ALLOC
 # define __RWSEM_DEP_MAP_INIT(lockname)			\
@@ -87,6 +90,34 @@ static inline void rwsem_assert_held_write_nolockdep(const struct rw_semaphore *
 	WARN_ON(!(atomic_long_read(&sem->count) & RWSEM_WRITER_LOCKED));
 }
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+/*
+ * Top waiter priority packed into sem->count bits 3..8: 0 = MAX_PRIO,
+ * 1..NICE_WIDTH = MAX_PRIO - prio (no extra struct rw_semaphore bytes).
+ */
+#define RWSEM_BOOST_PRIO_SHIFT	3
+#define RWSEM_BOOST_PRIO_BITS	6
+#define RWSEM_BOOST_PRIO_MASK	(((1UL << RWSEM_BOOST_PRIO_BITS) - 1) << \
+				 RWSEM_BOOST_PRIO_SHIFT)
+
+/**
+ * rwsem_top_waiter_prio - Priority of the most urgent waiter on @sem
+ * @sem: the rw_semaphore
+ *
+ * Lockless snapshot; RT and deadline waiters count as MAX_RT_PRIO.
+ *
+ * Return: the lowest waiter priority, or MAX_PRIO if no waiter asks
+ * for a boost.
+ */
+static inline int rwsem_top_waiter_prio(const struct rw_semaphore *sem)
+{
+	unsigned long count = atomic_long_read(&sem->count);
+
+	return MAX_PRIO - ((count & RWSEM_BOOST_PRIO_MASK) >>
+			   RWSEM_BOOST_PRIO_SHIFT);
+}
+#endif
+
 /* Common initializer macros and functions */
 
 #ifdef CONFIG_DEBUG_RWSEMS
diff --git a/kernel/locking/rwsem.c b/kernel/locking/rwsem.c
index 798a8db7636c..6d9b78a3d33a 100644
--- a/kernel/locking/rwsem.c
+++ b/kernel/locking/rwsem.c
@@ -221,6 +221,13 @@ static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
  * Bits 8-30 - 23-bit reader count
  * Bit  31   - read fail bit
  *
+ * With CONFIG_RWSEM_SCHED_BOOST, bits 3-8 hold the priority of the
+ * most urgent waiter (see rwsem_top_waiter_prio()) and the reader
+ * count starts at bit 9: 54 bits on 64-bit, 22 bits on 32-bit.  Like
+ * the handoff bit, the priority bits only change with wait_lock held.
+ * They are non-zero only while the waiters present bit is set and are
+ * cleared by the same atomic operation.
+ *
  * It is not likely that the most significant bit (read fail bit) will ever
  * be set. This guard bit is still checked anyway in the down_read() fastpath
  * just in case we need to use up more of the reader bits for other purpose
@@ -243,7 +250,12 @@ static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
 #define RWSEM_FLAG_HANDOFF	(1UL << 2)
 #define RWSEM_FLAG_READFAIL	(1UL << (BITS_PER_LONG - 1))
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+#define RWSEM_READER_SHIFT	(RWSEM_BOOST_PRIO_SHIFT + RWSEM_BOOST_PRIO_BITS)
+#else
+#define RWSEM_BOOST_PRIO_MASK	0UL
 #define RWSEM_READER_SHIFT	8
+#endif
 #define RWSEM_READER_BIAS	(1UL << RWSEM_READER_SHIFT)
 #define RWSEM_READER_MASK	(~(RWSEM_READER_BIAS - 1))
 #define RWSEM_WRITER_MASK	RWSEM_WRITER_LOCKED
@@ -251,6 +263,13 @@ static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
 #define RWSEM_READ_FAILED_MASK	(RWSEM_WRITER_MASK|RWSEM_FLAG_WAITERS|\
 				 RWSEM_FLAG_HANDOFF|RWSEM_FLAG_READFAIL)
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+static_assert(NICE_WIDTH < (1UL << RWSEM_BOOST_PRIO_BITS));
+static_assert((RWSEM_BOOST_PRIO_MASK &
+	       (RWSEM_WRITER_LOCKED | RWSEM_FLAG_WAITERS |
+		RWSEM_FLAG_HANDOFF | RWSEM_READER_MASK)) == 0);
+#endif
+
 /*
  * All writes to owner are protected by WRITE_ONCE() to make sure that
  * store tearing can't happen as optimistic spinners may read and use
@@ -465,6 +484,9 @@ struct rwsem_waiter {
 	enum rwsem_waiter_type type;
 	unsigned long timeout;
 	bool handoff_set;
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+	u8 boost_prio;
+#endif
 };
 
 enum rwsem_wake_type {
@@ -473,6 +495,142 @@ enum rwsem_wake_type {
 	RWSEM_WAKE_READ_OWNED	/* Waker thread holds the read lock */
 };
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+/*
+ * Sample current's priority for boost decisions before taking
+ * wait_lock, so recalc never chases w->task.  SCHED_IDLE ranks below
+ * nice 19 unless PI-boosted into RT, and nice -20 caps it to protect
+ * RT/DL.
+ */
+static inline void rwsem_waiter_init_prio(struct rwsem_waiter *waiter)
+{
+	int prio;
+
+	waiter->boost_prio = MAX_PRIO;
+	if (!static_branch_likely(&rwsem_boost_key))
+		return;
+
+	prio = READ_ONCE(current->prio);
+	if (READ_ONCE(current->policy) == SCHED_IDLE && prio >= MAX_RT_PRIO)
+		prio = MAX_PRIO;
+	waiter->boost_prio = max_t(int, prio, MAX_RT_PRIO);
+}
+
+static inline unsigned long
+rwsem_waiter_prio_bits(const struct rwsem_waiter *waiter)
+{
+	return (unsigned long)(MAX_PRIO - waiter->boost_prio) <<
+	       RWSEM_BOOST_PRIO_SHIFT;
+}
+
+/*
+ * Return the sem->count delta that publishes @waiter's priority, or 0
+ * if it does not outrank the queued waiters.  The published value is
+ * the maximum over the queue; wait_lock serializes all its updates.
+ */
+static inline long
+rwsem_waiter_prio_add_delta(struct rw_semaphore *sem,
+			    const struct rwsem_waiter *waiter)
+	__must_hold(&sem->wait_lock)
+{
+	unsigned long cur_bits, new_bits;
+
+	cur_bits = atomic_long_read(&sem->count) & RWSEM_BOOST_PRIO_MASK;
+	new_bits = rwsem_waiter_prio_bits(waiter);
+	if (new_bits <= cur_bits)
+		return 0;
+	return (long)(new_bits - cur_bits);
+}
+
+/*
+ * Waiters whose best encoded priority is @gone_bits left while others
+ * remain.  Only losing a top waiter can lower the published maximum,
+ * and no remaining waiter can beat it, so stop at the first one that
+ * still matches.  Return the sem->count delta relative to @cur_count.
+ */
+static long rwsem_waiter_prio_recalc_delta(struct rw_semaphore *sem,
+					   long cur_count,
+					   unsigned long gone_bits)
+	__must_hold(&sem->wait_lock)
+{
+	unsigned long top_bits = cur_count & RWSEM_BOOST_PRIO_MASK;
+	struct rwsem_waiter *first = sem->first_waiter, *w;
+	unsigned long bits;
+
+	if (top_bits == 0)
+		return 0;
+	if (gone_bits < top_bits)
+		return 0;
+
+	bits = rwsem_waiter_prio_bits(first);
+	list_for_each_entry(w, &first->list, list) {
+		if (bits >= top_bits)
+			break;
+		bits = max(bits, rwsem_waiter_prio_bits(w));
+	}
+	return (long)bits - (long)top_bits;
+}
+
+/* Publish @waiter's priority if it outranks the queued waiters. */
+static inline void rwsem_waiter_prio_add(struct rw_semaphore *sem,
+					 const struct rwsem_waiter *waiter)
+	__must_hold(&sem->wait_lock)
+{
+	long delta = rwsem_waiter_prio_add_delta(sem, waiter);
+
+	if (delta != 0)
+		atomic_long_add(delta, &sem->count);
+}
+
+/* Republish the top priority after @waiter left; others remain. */
+static inline void rwsem_waiter_prio_del(struct rw_semaphore *sem,
+					 const struct rwsem_waiter *waiter)
+	__must_hold(&sem->wait_lock)
+{
+	long delta;
+
+	delta = rwsem_waiter_prio_recalc_delta(sem,
+					       atomic_long_read(&sem->count),
+					       rwsem_waiter_prio_bits(waiter));
+	if (delta != 0)
+		atomic_long_add(delta, &sem->count);
+}
+#else
+static inline void rwsem_waiter_init_prio(struct rwsem_waiter *waiter)
+{
+}
+
+static inline unsigned long
+rwsem_waiter_prio_bits(const struct rwsem_waiter *waiter)
+{
+	return 0;
+}
+
+static inline long
+rwsem_waiter_prio_add_delta(struct rw_semaphore *sem,
+			    const struct rwsem_waiter *waiter)
+{
+	return 0;
+}
+
+static inline long rwsem_waiter_prio_recalc_delta(struct rw_semaphore *sem,
+						  long cur_count,
+						  unsigned long gone_bits)
+{
+	return 0;
+}
+
+static inline void rwsem_waiter_prio_add(struct rw_semaphore *sem,
+					 const struct rwsem_waiter *waiter)
+{
+}
+
+static inline void rwsem_waiter_prio_del(struct rw_semaphore *sem,
+					 const struct rwsem_waiter *waiter)
+{
+}
+#endif
+
 /*
  * The typical HZ value is either 250 or 1000. So set the minimum waiting
  * time to at least 4ms or 1 jiffy (if it is higher than 4ms) in the wait
@@ -502,6 +660,7 @@ bool __rwsem_del_waiter(struct rw_semaphore *sem, struct rwsem_waiter *waiter)
 						     struct rwsem_waiter, list);
 	}
 	list_del(&waiter->list);
+	rwsem_waiter_prio_del(sem, waiter);
 
 	return true;
 }
@@ -520,7 +679,8 @@ rwsem_del_waiter(struct rw_semaphore *sem, struct rwsem_waiter *waiter)
 	lockdep_assert_held(&sem->wait_lock);
 	if (__rwsem_del_waiter(sem, waiter))
 		return true;
-	atomic_long_andnot(RWSEM_FLAG_HANDOFF | RWSEM_FLAG_WAITERS, &sem->count);
+	atomic_long_andnot(RWSEM_FLAG_HANDOFF | RWSEM_FLAG_WAITERS |
+			   RWSEM_BOOST_PRIO_MASK, &sem->count);
 	return false;
 }
 
@@ -556,6 +716,7 @@ static void rwsem_mark_wake(struct rw_semaphore *sem,
 {
 	struct rwsem_waiter *waiter, *next;
 	long oldcount, woken = 0, adjustment = 0;
+	unsigned long woken_bits = 0;
 	struct list_head wlist;
 
 	lockdep_assert_held(&sem->wait_lock);
@@ -655,6 +816,7 @@ static void rwsem_mark_wake(struct rw_semaphore *sem,
 			continue;
 
 		woken++;
+		woken_bits = max(woken_bits, rwsem_waiter_prio_bits(waiter));
 		list_move_tail(&waiter->list, &wlist);
 		if (sem->first_waiter == waiter)
 			sem->first_waiter = next;
@@ -678,6 +840,7 @@ static void rwsem_mark_wake(struct rw_semaphore *sem,
 		adjustment -= RWSEM_FLAG_WAITERS;
 		if (oldcount & RWSEM_FLAG_HANDOFF)
 			adjustment -= RWSEM_FLAG_HANDOFF;
+		adjustment -= oldcount & RWSEM_BOOST_PRIO_MASK;
 	} else if (woken) {
 		/*
 		 * When we've woken a reader, we no longer need to force
@@ -685,6 +848,8 @@ static void rwsem_mark_wake(struct rw_semaphore *sem,
 		 */
 		if (oldcount & RWSEM_FLAG_HANDOFF)
 			adjustment -= RWSEM_FLAG_HANDOFF;
+		adjustment += rwsem_waiter_prio_recalc_delta(sem, oldcount,
+							     woken_bits);
 	}
 
 	if (adjustment)
@@ -787,7 +952,8 @@ static inline bool rwsem_try_write_lock(struct rw_semaphore *sem,
 			new &= ~RWSEM_FLAG_HANDOFF;
 
 			if (list_empty(&first->list))
-				new &= ~RWSEM_FLAG_WAITERS;
+				new &= ~(RWSEM_FLAG_WAITERS |
+					 RWSEM_BOOST_PRIO_MASK);
 		}
 	} while (!atomic_long_try_cmpxchg_acquire(&sem->count, &count, new));
 
@@ -1187,6 +1353,7 @@ rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int stat
 	waiter.type = RWSEM_WAITING_FOR_READ;
 	waiter.timeout = jiffies + RWSEM_WAIT_TIMEOUT;
 	waiter.handoff_set = false;
+	rwsem_waiter_init_prio(&waiter);
 
 	raw_spin_lock_irq(&sem->wait_lock);
 	first = sem->first_waiter;
@@ -1211,6 +1378,7 @@ rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int stat
 	} else {
 		list_add_tail(&waiter.list, &first->list);
 	}
+	adjustment += rwsem_waiter_prio_add_delta(sem, &waiter);
 
 	/* we're now waiting on the lock, but no longer actively locking */
 	count = atomic_long_add_return(adjustment, &sem->count);
@@ -1287,12 +1455,14 @@ rwsem_down_write_slowpath(struct rw_semaphore *sem, int state)
 	waiter.type = RWSEM_WAITING_FOR_WRITE;
 	waiter.timeout = jiffies + RWSEM_WAIT_TIMEOUT;
 	waiter.handoff_set = false;
+	rwsem_waiter_init_prio(&waiter);
 
 	raw_spin_lock_irq(&sem->wait_lock);
 
 	first = sem->first_waiter;
 	if (first) {
 		list_add_tail(&waiter.list, &first->list);
+		rwsem_waiter_prio_add(sem, &waiter);
 		rwsem_cond_wake_waiter(sem, atomic_long_read(&sem->count),
 				       &wake_q);
 		if (!wake_q_empty(&wake_q)) {
@@ -1307,7 +1477,8 @@ rwsem_down_write_slowpath(struct rw_semaphore *sem, int state)
 	} else {
 		INIT_LIST_HEAD(&waiter.list);
 		sem->first_waiter = &waiter;
-		atomic_long_or(RWSEM_FLAG_WAITERS, &sem->count);
+		atomic_long_or(RWSEM_FLAG_WAITERS |
+			       rwsem_waiter_prio_bits(&waiter), &sem->count);
 	}
 
 	/* wait until we successfully acquire the lock */
-- 
2.56.1.839.g22a8290db9-goog


^ permalink raw reply	[flat|nested] 9+ messages in thread

* [RFC PATCH v2 4/6] sched: Apply rwsem holder boost to the fair load weight
  2026-12-01  6:27 [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters Peng Huang
                   ` (2 preceding siblings ...)
  2026-12-01  6:27 ` [RFC PATCH v2 3/6] locking/rwsem: Publish the top waiter priority Peng Huang
@ 2026-12-01  6:27 ` Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 5/6] sched/fair: Boost rwsem holders with contended high-priority waiters Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 6/6] locking/rwsem: Add KUnit tests for scheduler priority boost Peng Huang
  5 siblings, 0 replies; 9+ messages in thread
From: Peng Huang @ 2026-12-01  6:27 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot
  Cc: Waiman Long, Dietmar Eggemann, Steven Rostedt, Ben Segall,
	Mel Gorman, Valentin Schneider, K Prateek Nayak, John Stultz,
	Suren Baghdasaryan, linux-kernel, linux-mm, Peng Huang

The previous patch publishes how urgent an rwsem's waiters are, but a
preempted holder still runs at its own weight and keeps them blocked.

Add p->rwsem_boost.prio (MAX_PRIO when none) and feed it into
set_load_weight().  p->prio, static_prio and rt_mutex PI are never
touched: a boost only raises the fair load weight (capped at nice -20)
and never leaves the fair class.

rwsem_boost_calc_prio() scans the held slots via
rwsem_top_waiter_prio() and boosts only when a waiter outranks the
holder.  On unlock, downgrade_write(), or a signal-interrupted read
wait, a boosted task recomputes without locks and takes rq->lock only
if its boost dropped, rescheduling if other fair tasks are runnable on
its CPU.  Leaving the fair class clears the boost; queued waiters also
sample their own boost so it propagates across rwsem chains.

The next patch adds the fair-class paths that apply the boost.

Signed-off-by: Peng Huang <penghuang@google.com>
---
 include/linux/rwsem.h  |  1 +
 include/linux/sched.h  |  5 +++
 init/init_task.c       |  5 +++
 kernel/locking/rwsem.c | 37 ++++++++++++++--
 kernel/sched/core.c    | 90 ++++++++++++++++++++++++++++++++++++++-
 kernel/sched/fair.c    | 97 ++++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h   | 42 ++++++++++++++++++
 7 files changed, 272 insertions(+), 5 deletions(-)

diff --git a/include/linux/rwsem.h b/include/linux/rwsem.h
index d8a49170efd2..30dfa2920dfa 100644
--- a/include/linux/rwsem.h
+++ b/include/linux/rwsem.h
@@ -370,6 +370,7 @@ void up_read_non_owner(struct rw_semaphore *sem) __releases_shared(sem);
 #ifdef CONFIG_RWSEM_SCHED_BOOST
 void rwsem_boost_untrack(struct rw_semaphore *sem);
 bool rwsem_boost_set(bool enable);
+void rwsem_boost_drop(void);
 #else
 static inline void rwsem_boost_untrack(struct rw_semaphore *sem)
 {
diff --git a/include/linux/sched.h b/include/linux/sched.h
index a98be7c4537d..92e32f58876e 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -840,6 +840,7 @@ struct task_ipi_mask { };
 /**
  * struct rwsem_sched_boost - per-task rw_semaphore boost state
  * @nr_held:	number of non-NULL entries in @held
+ * @prio:	fair priority lent by waiters on @held, MAX_PRIO if none
  * @held:	rw_semaphores held, one slot per tracked acquisition
  *
  * Only the task itself writes @nr_held and @held, so the lock
@@ -847,9 +848,13 @@ struct task_ipi_mask { };
  * be granted (a blocking reader fills it before it queues) and cleared
  * before the rwsem is released or the wait is abandoned, so a
  * non-NULL slot always names an rwsem the task holds or waits for.
+ *
+ * @prio is written under rq->lock; the task itself also reads it
+ * locklessly.
  */
 struct rwsem_sched_boost {
 	u8				nr_held;
+	u8				prio;
 	struct rw_semaphore		*held[RWSEM_SCHED_BOOST_SLOTS];
 };
 #endif
diff --git a/init/init_task.c b/init/init_task.c
index ce7c2b07d855..214d3f2ef8a0 100644
--- a/init/init_task.c
+++ b/init/init_task.c
@@ -134,6 +134,11 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = {
 		.time_slice	= RR_TIMESLICE,
 	},
 	.tasks		= LIST_HEAD_INIT(init_task.tasks),
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+	.rwsem_boost	= {
+		.prio		= MAX_PRIO,
+	},
+#endif
 #ifdef CONFIG_SMP
 	.pushable_tasks	= PLIST_NODE_INIT(init_task.pushable_tasks, MAX_PRIO),
 #endif
diff --git a/kernel/locking/rwsem.c b/kernel/locking/rwsem.c
index 6d9b78a3d33a..33fda82c2acc 100644
--- a/kernel/locking/rwsem.c
+++ b/kernel/locking/rwsem.c
@@ -104,7 +104,9 @@ static inline void rwsem_boost_track_trylock(struct rw_semaphore *sem)
  * another task can acquire or free @sem, scheduler inspection no
  * longer finds it.  Unlike tracking, ignore rwsem_boost_key and
  * irqs_disabled() so no slot outlives its lock; an acquire that was
- * not tracked can only end tracking early (losing boost).
+ * not tracked can only end tracking early (losing boost).  Unlock
+ * paths drop the boost themselves after the wakeup;
+ * rwsem_boost_untrack() does both for callers that hand @sem over.
  */
 static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
 {
@@ -127,16 +129,32 @@ static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
 	}
 }
 
+static inline void rwsem_boost_maybe_drop(void)
+{
+	/*
+	 * Check prio first so unboosted unlocks skip preempt_count.
+	 * rwsem_boost_drop() takes rq->lock only if the boost drops,
+	 * normally right after releasing the contended rwsem that set
+	 * it, where up_*() can already take pi_lock and rq->lock via
+	 * rwsem_wake().
+	 */
+	if (unlikely(READ_ONCE(current->rwsem_boost.prio) < MAX_PRIO &&
+		     in_task()))
+		rwsem_boost_drop();
+}
+
 /**
  * rwsem_boost_untrack - Stop tracking @sem as held by current
  * @sem: rwsem that current holds
  *
  * Call before another context can release @sem, e.g. an io_uring
- * completion that runs in a different task.  Task context only.
+ * completion that runs in a different task.  This also drops any
+ * boost that @sem gave current.  Task context only.
  */
 void rwsem_boost_untrack(struct rw_semaphore *sem)
 {
 	__rwsem_boost_untrack(sem);
+	rwsem_boost_maybe_drop();
 }
 EXPORT_SYMBOL_GPL(rwsem_boost_untrack);
 #else
@@ -151,6 +169,10 @@ static inline void rwsem_boost_track_trylock(struct rw_semaphore *sem)
 static inline void __rwsem_boost_untrack(struct rw_semaphore *sem)
 {
 }
+
+static inline void rwsem_boost_maybe_drop(void)
+{
+}
 #endif
 
 #ifndef CONFIG_PREEMPT_RT
@@ -499,7 +521,8 @@ enum rwsem_wake_type {
 /*
  * Sample current's priority for boost decisions before taking
  * wait_lock, so recalc never chases w->task.  SCHED_IDLE ranks below
- * nice 19 unless PI-boosted into RT, and nice -20 caps it to protect
+ * nice 19 unless PI-boosted into RT, a transitive rwsem boost counts
+ * without changing current->prio, and nice -20 caps it to protect
  * RT/DL.
  */
 static inline void rwsem_waiter_init_prio(struct rwsem_waiter *waiter)
@@ -513,6 +536,7 @@ static inline void rwsem_waiter_init_prio(struct rwsem_waiter *waiter)
 	prio = READ_ONCE(current->prio);
 	if (READ_ONCE(current->policy) == SCHED_IDLE && prio >= MAX_RT_PRIO)
 		prio = MAX_PRIO;
+	prio = min_t(int, prio, READ_ONCE(current->rwsem_boost.prio));
 	waiter->boost_prio = max_t(int, prio, MAX_RT_PRIO);
 }
 
@@ -1427,6 +1451,8 @@ rwsem_down_read_slowpath(struct rw_semaphore *sem, long count, unsigned int stat
 	__rwsem_boost_untrack(sem);
 	rwsem_del_wake_waiter(sem, &waiter, &wake_q);
 	__set_current_state(TASK_RUNNING);
+	/* Undo any boost that the signal wakeup took from the slot. */
+	rwsem_boost_maybe_drop();
 	lockevent_inc(rwsem_rlock_fail);
 	trace_contention_end(sem, -EINTR);
 	return ERR_PTR(-EINTR);
@@ -1707,6 +1733,9 @@ static inline void __up_read(struct rw_semaphore *sem)
 		rwsem_wake(sem);
 	}
 	preempt_enable();
+
+	/* Drop any boost after the wakeup, with preemption enabled. */
+	rwsem_boost_maybe_drop();
 }
 
 /*
@@ -1733,6 +1762,7 @@ static inline void __up_write(struct rw_semaphore *sem)
 		rwsem_wake(sem);
 	}
 	preempt_enable();
+	rwsem_boost_maybe_drop();
 }
 
 /*
@@ -1759,6 +1789,7 @@ static inline void __downgrade_write(struct rw_semaphore *sem)
 		rwsem_downgrade_wake(sem);
 	}
 	preempt_enable();
+	rwsem_boost_maybe_drop();
 }
 
 #else /* !CONFIG_PREEMPT_RT */
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index ea89471d4743..56e32d4ffc3c 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -39,6 +39,7 @@
 #include <linux/sched/nohz.h>
 #include <linux/sched/rseq_api.h>
 #include <linux/sched/rt.h>
+#include <linux/rwsem.h>
 
 #include <linux/context_tracking.h>
 #include <linux/cpuset.h>
@@ -1562,12 +1563,96 @@ int tg_nop(struct task_group *tg, void *data)
 }
 #endif
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+static inline void rwsem_boost_fork(struct task_struct *p)
+{
+	BUILD_BUG_ON(MAX_PRIO > U8_MAX);
+
+	memset(&p->rwsem_boost, 0, sizeof(p->rwsem_boost));
+	p->rwsem_boost.prio = MAX_PRIO;
+
+	/*
+	 * dup_task_struct() copied current->se.load without rq->lock;
+	 * it may be boosted or torn.  Recompute it so the child neither
+	 * inherits the boost nor seeds its PELT load_avg from it.
+	 */
+	set_load_weight(p, false);
+}
+
+/**
+ * rwsem_boost_calc_prio - Compute @p's rwsem boost priority
+ * @p: task whose held rwsems are inspected
+ *
+ * Callers must ensure @p cannot run elsewhere (see struct
+ * rwsem_sched_boost).
+ *
+ * Return: the lowest fair priority of any waiter on @p's held rwsems
+ * if it outranks @p, or MAX_PRIO otherwise.
+ */
+int rwsem_boost_calc_prio(struct task_struct *p)
+{
+	struct rwsem_sched_boost *b = &p->rwsem_boost;
+	int best = MAX_PRIO;
+	int i;
+
+	if (!rwsem_boost_has_headroom(p))
+		return MAX_PRIO;
+
+	if (READ_ONCE(b->nr_held) == 0)
+		return MAX_PRIO;
+
+	for (i = 0; i < RWSEM_SCHED_BOOST_SLOTS; i++) {
+		struct rw_semaphore *sem = READ_ONCE(b->held[i]);
+		int wprio;
+
+		if (!sem)
+			continue;
+		wprio = rwsem_top_waiter_prio(sem);
+		if (wprio < best)
+			best = wprio;
+	}
+
+	/* Cap at nice -20; boost only if the waiter outranks @p. */
+	best = max_t(int, best, MAX_RT_PRIO);
+	return best < rwsem_boost_base_prio(p) ? best : MAX_PRIO;
+}
+
+/**
+ * rwsem_boost_drop - Drop current's rwsem boost after releasing a lock
+ *
+ * Only current writes its held[] and it still holds every rwsem listed
+ * there, so the boost can be recomputed without rq->lock.  Take the
+ * lock only if the boost dropped: releasing an rwsem that did not set
+ * it changes nothing, and upgrades are left to enqueue, preemption and
+ * the tick.
+ */
+void rwsem_boost_drop(void)
+{
+	struct task_struct *p = current;
+	struct rq_flags rf;
+	struct rq *rq;
+
+	if (rwsem_boost_calc_prio(p) <= READ_ONCE(p->rwsem_boost.prio))
+		return;
+
+	rq = task_rq_lock(p, &rf);
+	if (p->sched_class == &fair_sched_class) {
+		update_rq_clock(rq);
+		rwsem_boost_drop_fair(rq, p);
+	}
+	task_rq_unlock(rq, p, &rf);
+}
+#else
+static inline void rwsem_boost_fork(struct task_struct *p) { }
+#endif
+
 void set_load_weight(struct task_struct *p, bool update_load)
 {
-	int prio = p->static_prio - MAX_RT_PRIO;
+	int prio = rwsem_boost_effective_prio(p) - MAX_RT_PRIO;
 	struct load_weight lw;
 
-	if (task_has_idle_policy(p)) {
+	/* Boosted SCHED_IDLE holders use normal nice weights. */
+	if (task_has_idle_policy(p) && !rwsem_boost_active(p)) {
 		lw.weight = scale_load(WEIGHT_IDLEPRIO);
 		lw.inv_weight = WMULT_IDLEPRIO;
 	} else {
@@ -4916,6 +5001,7 @@ int sched_fork(u64 clone_flags, struct task_struct *p)
 	 * Make sure we do not leak PI boosting priority to the child.
 	 */
 	p->prio = current->normal_prio;
+	rwsem_boost_fork(p);
 
 	uclamp_fork(p);
 
diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c
index 2d9d3d686261..f755ee810ce2 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -8199,6 +8199,102 @@ static inline void update_curr_eevdf(struct cfs_rq *cfs_rq)
 	update_curr(cfs_rq_of(cfs_rq->curr));
 }
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+/*
+ * Recompute fair task @p's load weight from its held rwsems without
+ * touching p->prio, so rt_mutex PI and syscall priorities stay
+ * orthogonal.  Callers hold @rq->lock with @p attached to cfs_rq->avg
+ * and not running elsewhere (see struct rwsem_sched_boost).
+ */
+static bool rwsem_boost_reweight_fair(struct rq *rq, struct task_struct *p)
+{
+	struct sched_entity *se = &p->se;
+	int new_boost;
+
+	lockdep_assert_rq_held(rq);
+
+	new_boost = rwsem_boost_calc_prio(p);
+	if (new_boost == p->rwsem_boost.prio)
+		return false;
+
+	/* Sync @se and its cfs_rq PELT before reweight_entity(). */
+	update_load_avg(cfs_rq_of(se), se, 0);
+	WRITE_ONCE(p->rwsem_boost.prio, new_boost);
+	set_load_weight(p, true);
+	return true;
+}
+
+/*
+ * Clear @p's rwsem boost when it leaves fair_sched_class, so unlocking
+ * outside CFS never leaves a stale weight behind.  This runs before
+ * detach_task_cfs_rq(), so handle PELT like detach_entity_cfs_rq().
+ */
+static void rwsem_boost_clear_fair(struct rq *rq, struct task_struct *p)
+{
+	struct sched_entity *se = &p->se;
+
+	lockdep_assert_rq_held(rq);
+
+	if (!rwsem_boost_active(p))
+		return;
+
+	/* Wakeup still pending: no cfs_rq holds this load yet. */
+	if (!se->avg.last_update_time) {
+		WRITE_ONCE(p->rwsem_boost.prio, MAX_PRIO);
+		set_load_weight(p, false);
+		return;
+	}
+	/* Sync @se and its cfs_rq PELT before reweight_entity(). */
+	update_load_avg(cfs_rq_of(se), se, 0);
+	WRITE_ONCE(p->rwsem_boost.prio, MAX_PRIO);
+	set_load_weight(p, true);
+}
+
+/*
+ * Cancel @curr's slice protection and resched it.  Not lazy: a boost
+ * change, like a priority change in prio_changed_fair(), should not
+ * wait for the next tick.
+ */
+static void rwsem_boost_resched_fair(struct rq *rq, struct task_struct *curr)
+{
+	cancel_protect_slice(&curr->se);
+	resched_curr(rq);
+}
+
+/* True if running @p lost weight while other fair tasks wait. */
+static inline bool rwsem_boost_should_resched_fair(struct rq *rq,
+						   struct task_struct *p,
+						   int old_prio)
+{
+	return rwsem_boost_effective_prio(p) > old_prio &&
+	       task_current_donor(rq, p) && rq->cfs.h_nr_queued > 1;
+}
+
+/*
+ * Refresh running @p's boost.  Return true if it lost the boost while
+ * other fair tasks wait, so the caller should reschedule.
+ */
+static bool rwsem_boost_refresh_curr_fair(struct rq *rq,
+					  struct task_struct *p)
+{
+	int old_prio = rwsem_boost_effective_prio(p);
+
+	if (!rwsem_boost_reweight_fair(rq, p))
+		return false;
+	return rwsem_boost_should_resched_fair(rq, p, old_prio);
+}
+
+/* Refresh @p's boost weight after rwsem unlock or downgrade_write(). */
+void rwsem_boost_drop_fair(struct rq *rq, struct task_struct *p)
+{
+	if (rwsem_boost_refresh_curr_fair(rq, p))
+		rwsem_boost_resched_fair(rq, p);
+}
+#else
+static inline void rwsem_boost_clear_fair(struct rq *rq,
+					  struct task_struct *p) { }
+#endif
+
 /*
  * The enqueue_task method is called before nr_running is
  * increased. Here we update the fair scheduling stats and
@@ -15538,6 +15634,7 @@ static void switching_from_fair(struct rq *rq, struct task_struct *p)
 
 static void switched_from_fair(struct rq *rq, struct task_struct *p)
 {
+	rwsem_boost_clear_fair(rq, p);
 	detach_task_cfs_rq(p);
 }
 
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 32f76551a0c5..058311c19cc0 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -2848,6 +2848,7 @@ struct sched_class {
 	/*
 	 * set_load_weight: task_rq_lock + sched_change
 	 * __setscheduler_parms: task_rq_lock + sched_change
+	 * rwsem boost (fair): rq->lock, @task may be queued or running
 	 */
 	void (*reweight_task)(struct rq *this_rq, struct task_struct *task,
 			      const struct load_weight *lw);
@@ -4420,4 +4421,45 @@ void sched_push_current_non_preferred_cpu(struct rq *rq);
 static inline void sched_push_current_non_preferred_cpu(struct rq *rq) { }
 #endif
 
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+static inline bool rwsem_boost_active(const struct task_struct *p)
+{
+	return p->rwsem_boost.prio < MAX_PRIO;
+}
+
+/*
+ * Base CFS prio for boost decisions.  SCHED_IDLE tasks keep
+ * static_prio == NICE_TO_PRIO(0) but rank below nice 19.
+ */
+static inline int rwsem_boost_base_prio(const struct task_struct *p)
+{
+	return idle_policy(p->policy) ? MAX_PRIO : p->static_prio;
+}
+
+/* True if @p is below nice -20 and can still be boosted. */
+static inline bool rwsem_boost_has_headroom(const struct task_struct *p)
+{
+	return rwsem_boost_base_prio(p) > MAX_RT_PRIO;
+}
+
+/* Effective fair prio; MAX_PRIO for an unboosted SCHED_IDLE task. */
+static inline int rwsem_boost_effective_prio(const struct task_struct *p)
+{
+	return min_t(int, rwsem_boost_base_prio(p), p->rwsem_boost.prio);
+}
+
+int rwsem_boost_calc_prio(struct task_struct *p);
+void rwsem_boost_drop_fair(struct rq *rq, struct task_struct *p);
+#else
+static inline bool rwsem_boost_active(const struct task_struct *p)
+{
+	return false;
+}
+
+static inline int rwsem_boost_effective_prio(const struct task_struct *p)
+{
+	return p->static_prio;
+}
+#endif
+
 #endif /* _KERNEL_SCHED_SCHED_H */
-- 
2.56.1.839.g22a8290db9-goog


^ permalink raw reply	[flat|nested] 9+ messages in thread

* [RFC PATCH v2 5/6] sched/fair: Boost rwsem holders with contended high-priority waiters
  2026-12-01  6:27 [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters Peng Huang
                   ` (3 preceding siblings ...)
  2026-12-01  6:27 ` [RFC PATCH v2 4/6] sched: Apply rwsem holder boost to the fair load weight Peng Huang
@ 2026-12-01  6:27 ` Peng Huang
  2026-12-01  6:27 ` [RFC PATCH v2 6/6] locking/rwsem: Add KUnit tests for scheduler priority boost Peng Huang
  5 siblings, 0 replies; 9+ messages in thread
From: Peng Huang @ 2026-12-01  6:27 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot
  Cc: Waiman Long, Dietmar Eggemann, Steven Rostedt, Ben Segall,
	Mel Gorman, Valentin Schneider, K Prateek Nayak, John Stultz,
	Suren Baghdasaryan, linux-kernel, linux-mm, Peng Huang

A preempted fair task holding an rwsem keeps higher-priority waiters
blocked until it runs again, and for readers the waiters cannot even
tell whom to boost.

Track runnable fair holders on per-CPU rq->rwsem_holders when enqueued
or preempted, and refresh their boost then and at each tick, all
within fair.c so uncontended lock paths never touch the list.  A tick
that raises a queued holder's boost reschedules current if the holder
now outranks it and is eligible.

Another task's held[] is read only under its rq->lock while it is not
running elsewhere, so its rwsems cannot be released meanwhile.
Holders unlink on any dequeue (including delayed dequeue, throttling,
and class switches).  Tasks entering fair, mutex-blocked Proxy
Execution donors, and remotely running tasks are linked without
reweighting so the tick boosts them once runnable.  Under Proxy
Execution, put_prev_task() also links a fair execution context when
its donor is fair; under a non-fair donor, it waits for its next
enqueue or preemption.

Each tick scans at most 16 queued holders (rotating the list for
fairness) to keep rq->lock work bounded, so a queued holder normally
waits up to one tick.

Signed-off-by: Peng Huang <penghuang@google.com>
---
 include/linux/sched.h |   8 +-
 init/init_task.c      |   1 +
 kernel/sched/core.c   |   2 +
 kernel/sched/fair.c   | 229 ++++++++++++++++++++++++++++++++++++++++++
 kernel/sched/sched.h  |  17 ++++
 5 files changed, 255 insertions(+), 2 deletions(-)

diff --git a/include/linux/sched.h b/include/linux/sched.h
index 92e32f58876e..8b2889ce7952 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -842,6 +842,7 @@ struct task_ipi_mask { };
  * @nr_held:	number of non-NULL entries in @held
  * @prio:	fair priority lent by waiters on @held, MAX_PRIO if none
  * @held:	rw_semaphores held, one slot per tracked acquisition
+ * @rq_node:	entry on rq->rwsem_holders, protected by rq->lock
  *
  * Only the task itself writes @nr_held and @held, so the lock
  * fastpaths need no atomics.  A slot is filled before the rwsem can
@@ -849,13 +850,16 @@ struct task_ipi_mask { };
  * before the rwsem is released or the wait is abandoned, so a
  * non-NULL slot always names an rwsem the task holds or waits for.
  *
- * @prio is written under rq->lock; the task itself also reads it
- * locklessly.
+ * Other tasks read @held only under the task's rq->lock while it is
+ * not running, so none of those rwsems can be released or freed
+ * meanwhile.  @prio is written under rq->lock; the task itself also
+ * reads it locklessly.
  */
 struct rwsem_sched_boost {
 	u8				nr_held;
 	u8				prio;
 	struct rw_semaphore		*held[RWSEM_SCHED_BOOST_SLOTS];
+	struct list_head		rq_node;
 };
 #endif
 
diff --git a/init/init_task.c b/init/init_task.c
index 214d3f2ef8a0..507540e50657 100644
--- a/init/init_task.c
+++ b/init/init_task.c
@@ -137,6 +137,7 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = {
 #ifdef CONFIG_RWSEM_SCHED_BOOST
 	.rwsem_boost	= {
 		.prio		= MAX_PRIO,
+		.rq_node	= LIST_HEAD_INIT(init_task.rwsem_boost.rq_node),
 	},
 #endif
 #ifdef CONFIG_SMP
diff --git a/kernel/sched/core.c b/kernel/sched/core.c
index 56e32d4ffc3c..288a8efcfb9d 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -1570,6 +1570,7 @@ static inline void rwsem_boost_fork(struct task_struct *p)
 
 	memset(&p->rwsem_boost, 0, sizeof(p->rwsem_boost));
 	p->rwsem_boost.prio = MAX_PRIO;
+	INIT_LIST_HEAD(&p->rwsem_boost.rq_node);
 
 	/*
 	 * dup_task_struct() copied current->se.load without rq->lock;
@@ -9168,6 +9169,7 @@ void __init sched_init(void)
 		rq->max_idle_balance_cost = sysctl_sched_migration_cost;
 
 		INIT_LIST_HEAD(&rq->cfs_tasks);
+		rwsem_boost_rq_init(rq);
 
 		rq_attach_root(rq, &def_root_domain);
 #ifdef CONFIG_NO_HZ_COMMON
diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c
index f755ee810ce2..08fbab673893 100644
--- a/kernel/sched/fair.c
+++ b/kernel/sched/fair.c
@@ -8270,6 +8270,27 @@ static inline bool rwsem_boost_should_resched_fair(struct rq *rq,
 	       task_current_donor(rq, p) && rq->cfs.h_nr_queued > 1;
 }
 
+/* Link runnable rwsem holder @p onto rq->rwsem_holders. */
+static inline void rwsem_boost_rq_add(struct rq *rq, struct task_struct *p)
+{
+	if (list_empty(&p->rwsem_boost.rq_node))
+		list_add_tail(&p->rwsem_boost.rq_node, &rq->rwsem_holders);
+}
+
+/* Unlink @p from rq->rwsem_holders when leaving the runqueue. */
+static inline void rwsem_boost_rq_del(struct task_struct *p)
+{
+	if (!list_empty(&p->rwsem_boost.rq_node))
+		list_del_init(&p->rwsem_boost.rq_node);
+}
+
+/* True if @p holds an rwsem and could still be boosted by the tick. */
+static inline bool rwsem_boost_needs_scan(const struct task_struct *p)
+{
+	return READ_ONCE(p->rwsem_boost.nr_held) != 0 &&
+	       rwsem_boost_has_headroom(p);
+}
+
 /*
  * Refresh running @p's boost.  Return true if it lost the boost while
  * other fair tasks wait, so the caller should reschedule.
@@ -8279,6 +8300,8 @@ static bool rwsem_boost_refresh_curr_fair(struct rq *rq,
 {
 	int old_prio = rwsem_boost_effective_prio(p);
 
+	if (!rwsem_boost_needs_scan(p))
+		rwsem_boost_rq_del(p);
 	if (!rwsem_boost_reweight_fair(rq, p))
 		return false;
 	return rwsem_boost_should_resched_fair(rq, p, old_prio);
@@ -8290,9 +8313,206 @@ void rwsem_boost_drop_fair(struct rq *rq, struct task_struct *p)
 	if (rwsem_boost_refresh_curr_fair(rq, p))
 		rwsem_boost_resched_fair(rq, p);
 }
+
+/* True if @p holds any rwsem or still carries an active boost. */
+static inline bool rwsem_boost_holding_or_active(const struct task_struct *p)
+{
+	return unlikely(READ_ONCE(p->rwsem_boost.nr_held) != 0 ||
+			rwsem_boost_active(p));
+}
+
+/*
+ * True if @p is runnable on_rq, not sleeping-delayed, not proxy-blocked
+ * on a mutex, and not running remotely.  Test se.on_rq rather than
+ * task_on_rq_queued(): sched_change_begin() dequeues the task before
+ * put_prev_task() without clearing p->on_rq.
+ */
+static inline bool rwsem_boost_can_inspect_fair(struct rq *rq,
+						struct task_struct *p)
+{
+	if (!p->se.on_rq)
+		return false;
+	if (p->se.sched_delayed)
+		return false;
+	if (task_is_blocked(p))
+		return false;
+	if (p != current && task_on_cpu(rq, p))
+		return false;
+	return true;
+}
+
+/*
+ * Link queued holder @p onto rq->rwsem_holders without reweighting it:
+ * a class switch before attach_task_cfs_rq(), a mutex-blocked proxy
+ * donor, or a proxy execution context that may run elsewhere.  Reads
+ * only @p's nr_held, never held[].
+ */
+static inline void rwsem_boost_link_fair(struct rq *rq, struct task_struct *p)
+{
+	if (!p->se.on_rq)
+		return;
+	if (p->se.sched_delayed)
+		return;
+	if (!rwsem_boost_needs_scan(p))
+		return;
+	rwsem_boost_rq_add(rq, p);
+}
+
+/* Sync @p on rq->rwsem_holders and refresh its boosted load weight. */
+static bool rwsem_boost_update_fair(struct rq *rq, struct task_struct *p)
+{
+	if (rwsem_boost_needs_scan(p))
+		rwsem_boost_rq_add(rq, p);
+	else
+		rwsem_boost_rq_del(p);
+	return rwsem_boost_reweight_fair(rq, p);
+}
+
+/* True if boosted, queued fair task @p should preempt @curr. */
+static inline bool
+rwsem_boost_should_preempt_fair(struct rq *rq, struct task_struct *p,
+				const struct task_struct *curr)
+{
+	if (p->rwsem_boost.prio >= rwsem_boost_effective_prio(curr))
+		return false;
+	/* Only task entities are on the EEVDF timeline, &rq->cfs. */
+	return entity_eligible(&rq->cfs, &p->se);
+}
+
+/*
+ * Track held-rwsem task @p on enqueue and refresh its load weight;
+ * called at the end of enqueue_task_fair(), once PELT and a delayed
+ * requeue are settled.
+ */
+static inline void rwsem_boost_enqueue_fair(struct rq *rq,
+					    struct task_struct *p,
+					    int flags)
+{
+	if (!rwsem_boost_holding_or_active(p))
+		return;
+
+	/*
+	 * A class switch attaches PELT only in switched_to_fair(): link
+	 * the task now and let the tick apply the boost.
+	 */
+	if (flags & ENQUEUE_CLASS) {
+		rwsem_boost_link_fair(rq, p);
+		return;
+	}
+	/*
+	 * Link a mutex-blocked proxy donor or remotely running task
+	 * without reading held[], so the tick catches it once runnable.
+	 */
+	if (!rwsem_boost_can_inspect_fair(rq, p)) {
+		rwsem_boost_link_fair(rq, p);
+		return;
+	}
+
+	rwsem_boost_update_fair(rq, p);
+}
+
+/*
+ * Under PROXY_EXEC with a fair donor, @prev is the donor and rq->curr
+ * ran on its behalf.  Link that execution context if it took an rwsem
+ * while running, so the tick can boost it once it waits for the CPU.
+ * Non-fair donors dispatch put_prev_task() through their own class, so
+ * a fair proxy context waits for its next enqueue or own preemption.
+ */
+static inline void rwsem_boost_put_proxy_fair(struct rq *rq,
+					      struct task_struct *prev)
+{
+	struct task_struct *exec = rq->curr;
+
+	if (!sched_proxy_exec())
+		return;
+	if (exec == prev)
+		return;
+	if (exec->sched_class != &fair_sched_class)
+		return;
+	rwsem_boost_link_fair(rq, exec);
+}
+
+/*
+ * Track a preempted task that acquired an rwsem while running (so
+ * enqueue_task_fair() never saw nr_held > 0) and apply any boost.
+ */
+static inline void rwsem_boost_put_prev_fair(struct rq *rq,
+					     struct task_struct *prev)
+{
+	rwsem_boost_put_proxy_fair(rq, prev);
+
+	if (!rwsem_boost_holding_or_active(prev))
+		return;
+	/*
+	 * A PROXY_EXEC mutex-blocked task stays on_rq: link it without
+	 * reweighting, so the tick sees it after an in-place wakeup.
+	 */
+	if (task_is_blocked(prev)) {
+		rwsem_boost_link_fair(rq, prev);
+		return;
+	}
+	if (rwsem_boost_can_inspect_fair(rq, prev))
+		rwsem_boost_update_fair(rq, prev);
+}
+
+#define RWSEM_BOOST_TICK_BUDGET		16
+
+/* Refresh boost for running @curr and queued rwsem holders on tick. */
+static void rwsem_boost_tick_fair(struct rq *rq, struct task_struct *curr)
+{
+	int budget = RWSEM_BOOST_TICK_BUDGET;
+	struct task_struct *p, *next;
+	bool resched = false;
+
+	/*
+	 * Refresh running @curr without linking it: preemption links
+	 * it if it is preempted while still holding an rwsem.
+	 */
+	if (rwsem_boost_holding_or_active(curr) &&
+	    rwsem_boost_can_inspect_fair(rq, curr))
+		resched = rwsem_boost_refresh_curr_fair(rq, curr);
+
+	list_for_each_entry_safe(p, next, &rq->rwsem_holders,
+				 rwsem_boost.rq_node) {
+		int old_prio;
+
+		if (budget-- == 0) {
+			/* Resume from @p next tick; keeps rq->lock O(1). */
+			list_rotate_to_front(&p->rwsem_boost.rq_node,
+					     &rq->rwsem_holders);
+			break;
+		}
+
+		if (p == curr) {
+			if (!rwsem_boost_needs_scan(curr))
+				rwsem_boost_rq_del(curr);
+			continue;
+		}
+		if (!rwsem_boost_can_inspect_fair(rq, p))
+			continue;
+
+		old_prio = p->rwsem_boost.prio;
+		if (rwsem_boost_update_fair(rq, p) &&
+		    p->rwsem_boost.prio < old_prio &&
+		    !task_current(rq, p) &&
+		    rwsem_boost_should_preempt_fair(rq, p, curr))
+			resched = true;
+	}
+
+	if (resched)
+		rwsem_boost_resched_fair(rq, curr);
+}
 #else
 static inline void rwsem_boost_clear_fair(struct rq *rq,
 					  struct task_struct *p) { }
+static inline void rwsem_boost_rq_del(struct task_struct *p) { }
+static inline void rwsem_boost_enqueue_fair(struct rq *rq,
+					    struct task_struct *p,
+					    int flags) { }
+static inline void rwsem_boost_put_prev_fair(struct rq *rq,
+					     struct task_struct *prev) { }
+static inline void rwsem_boost_tick_fair(struct rq *rq,
+					 struct task_struct *curr) { }
 #endif
 
 /*
@@ -8326,6 +8546,7 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
 
 	if (flags & ENQUEUE_DELAYED) {
 		requeue_delayed_entity(cfs_rq, se);
+		rwsem_boost_enqueue_fair(rq, p, flags);
 		return;
 	}
 
@@ -8383,6 +8604,7 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
 	assert_list_leaf_cfs_rq(rq);
 
 	hrtick_update(rq);
+	rwsem_boost_enqueue_fair(rq, p, flags);
 }
 
 static void dequeue_hierarchy(struct task_struct *p, int flags)
@@ -8514,6 +8736,9 @@ static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  */
 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
 {
+	/* Unlink first: throttled and delayed dequeues return early. */
+	rwsem_boost_rq_del(p);
+
 	if (task_is_throttled(p)) {
 		dequeue_throttled_task(p, flags);
 		return true;
@@ -10516,6 +10741,8 @@ static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct t
 	cfs_rq->curr = NULL;
 	if (se->on_rq)
 		__enqueue_entity(cfs_rq, se);
+
+	rwsem_boost_put_prev_fair(rq, prev);
 }
 
 /*
@@ -15505,6 +15732,8 @@ static void task_tick_fair(struct rq *rq, struct task_struct *curr, int hrtick)
 	update_misfit_status(curr, rq);
 	check_update_overutilized_status(task_rq(curr));
 
+	rwsem_boost_tick_fair(rq, curr);
+
 	task_tick_core(rq, curr);
 }
 
diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h
index 058311c19cc0..3d7bf08223bc 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -1336,6 +1336,14 @@ struct rq {
 	int			online;
 
 	struct list_head cfs_tasks;
+#ifdef CONFIG_RWSEM_SCHED_BOOST
+	/*
+	 * Fair tasks holding rwsems, protected by rq->lock.  They leave
+	 * on dequeue and class switch; tasks that stopped holding are
+	 * dropped lazily by the tick.
+	 */
+	struct list_head	rwsem_holders;
+#endif
 
 	struct sched_avg	avg_rt;
 	struct sched_avg	avg_dl;
@@ -4450,6 +4458,11 @@ static inline int rwsem_boost_effective_prio(const struct task_struct *p)
 
 int rwsem_boost_calc_prio(struct task_struct *p);
 void rwsem_boost_drop_fair(struct rq *rq, struct task_struct *p);
+
+static inline void rwsem_boost_rq_init(struct rq *rq)
+{
+	INIT_LIST_HEAD(&rq->rwsem_holders);
+}
 #else
 static inline bool rwsem_boost_active(const struct task_struct *p)
 {
@@ -4460,6 +4473,10 @@ static inline int rwsem_boost_effective_prio(const struct task_struct *p)
 {
 	return p->static_prio;
 }
+
+static inline void rwsem_boost_rq_init(struct rq *rq)
+{
+}
 #endif
 
 #endif /* _KERNEL_SCHED_SCHED_H */
-- 
2.56.1.839.g22a8290db9-goog


^ permalink raw reply	[flat|nested] 9+ messages in thread

* [RFC PATCH v2 6/6] locking/rwsem: Add KUnit tests for scheduler priority boost
  2026-12-01  6:27 [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters Peng Huang
                   ` (4 preceding siblings ...)
  2026-12-01  6:27 ` [RFC PATCH v2 5/6] sched/fair: Boost rwsem holders with contended high-priority waiters Peng Huang
@ 2026-12-01  6:27 ` Peng Huang
  5 siblings, 0 replies; 9+ messages in thread
From: Peng Huang @ 2026-12-01  6:27 UTC (permalink / raw)
  To: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot
  Cc: Waiman Long, Dietmar Eggemann, Steven Rostedt, Ben Segall,
	Mel Gorman, Valentin Schneider, K Prateek Nayak, John Stultz,
	Suren Baghdasaryan, linux-kernel, linux-mm, Peng Huang,
	Andrew Morton

Add a KUnit suite (16 cases, 20 tests) covering per-task slot tracking
and sem->count priority packing (unlock order, overflow, untrack,
runtime disable, killed queued readers), fair boost transitions
(wakeup, downgrade_write, SCHED_IDLE, renice, fair/RT class switches,
transitive chains, PELT sync on reweight, Proxy Execution blocked
donors, no boost without contention), and a pinned-CPU A/B inversion
test (nice -10 writer waits about 40 ms instead of about 2 s on UML).

Passes on UML, x86_64 QEMU (-smp 4, PREEMPT_LAZY), and with
CONFIG_SCHED_PROXY_EXEC=y.  Timing cases use KUNIT_CASE_SLOW; the
fastpath benchmark runs only with rwsem_sched_boost_test.benchmark=1.

Signed-off-by: Peng Huang <penghuang@google.com>
---
 kernel/locking/Makefile                 |    1 +
 kernel/locking/rwsem_sched_boost_test.c | 1468 +++++++++++++++++++++++
 lib/Kconfig.debug                       |   17 +
 3 files changed, 1486 insertions(+)
 create mode 100644 kernel/locking/rwsem_sched_boost_test.c

diff --git a/kernel/locking/Makefile b/kernel/locking/Makefile
index cee1901d4cff..3df6ae1f1707 100644
--- a/kernel/locking/Makefile
+++ b/kernel/locking/Makefile
@@ -37,4 +37,5 @@ obj-$(CONFIG_DEBUG_SPINLOCK) += spinlock_debug.o
 obj-$(CONFIG_QUEUED_RWLOCKS) += qrwlock.o
 obj-$(CONFIG_LOCK_TORTURE_TEST) += locktorture.o
 obj-$(CONFIG_WW_MUTEX_SELFTEST) += test-ww_mutex.o
+obj-$(CONFIG_RWSEM_SCHED_BOOST_KUNIT_TEST) += rwsem_sched_boost_test.o
 obj-$(CONFIG_LOCK_EVENT_COUNTS) += lock_events.o
diff --git a/kernel/locking/rwsem_sched_boost_test.c b/kernel/locking/rwsem_sched_boost_test.c
new file mode 100644
index 000000000000..e91e8504c5d9
--- /dev/null
+++ b/kernel/locking/rwsem_sched_boost_test.c
@@ -0,0 +1,1468 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * KUnit tests for rw_semaphore per-task hold tracking and scheduler
+ * priority boosting.
+ */
+
+#include <kunit/test.h>
+#include <linux/atomic.h>
+#include <linux/completion.h>
+#include <linux/cpumask.h>
+#include <linux/delay.h>
+#include <linux/kthread.h>
+#include <linux/ktime.h>
+#include <linux/lockdep.h>
+#include <linux/math64.h>
+#include <linux/moduleparam.h>
+#include <linux/mutex.h>
+#include <linux/rwsem.h>
+#include <linux/sched.h>
+#include <linux/sched/signal.h>
+#include <linux/slab.h>
+#include <uapi/linux/sched/types.h>
+
+static bool saved_rwsem_boost_enabled;
+
+/* Opt-in benchmark: boot with rwsem_sched_boost_test.benchmark=1. */
+static bool benchmark;
+module_param(benchmark, bool, 0444);
+MODULE_PARM_DESC(benchmark, "Run the uncontended fastpath benchmark");
+
+static int rwsem_boost_suite_init(struct kunit_suite *suite)
+{
+	saved_rwsem_boost_enabled = rwsem_boost_set(true);
+	return 0;
+}
+
+static void rwsem_boost_suite_exit(struct kunit_suite *suite)
+{
+	rwsem_boost_set(saved_rwsem_boost_enabled);
+}
+
+static bool task_holds_rwsem(const struct task_struct *p,
+			     const struct rw_semaphore *sem)
+{
+	int i;
+
+	for (i = 0; i < RWSEM_SCHED_BOOST_SLOTS; i++) {
+		if (READ_ONCE(p->rwsem_boost.held[i]) == sem)
+			return true;
+	}
+	return false;
+}
+
+/* Poll @cond every 1-2 ms until it holds or @timeout_ms expires. */
+#define poll_until(cond, timeout_ms)					\
+({									\
+	unsigned long __deadline = jiffies + msecs_to_jiffies(timeout_ms); \
+	bool __ok;							\
+									\
+	while (!(__ok = (cond)) && !time_after(jiffies, __deadline))	\
+		usleep_range(1000, 2000);				\
+	__ok;								\
+})
+
+/*
+ * Poll until a contender queues on @sem.  Check the wait list rather
+ * than the published waiter priority, which stays MAX_PRIO while the
+ * boost is disabled (the A/B control runs).
+ */
+static bool wait_for_rwsem_waiter(struct rw_semaphore *sem, int timeout_ms)
+{
+	return poll_until(rwsem_is_contended(sem), timeout_ms);
+}
+
+static bool wait_for_waiter_prio(struct rw_semaphore *sem, int expected,
+				 int timeout_ms)
+{
+	return poll_until(rwsem_top_waiter_prio(sem) == expected, timeout_ms);
+}
+
+static bool wait_for_task_sleep(struct task_struct *tsk, int timeout_ms)
+{
+	return poll_until(READ_ONCE(tsk->__state) == TASK_UNINTERRUPTIBLE,
+			  timeout_ms);
+}
+
+/* Spin without sleeping until a tick or preemption applies @expected. */
+static void spin_wait_boost_prio(int expected, int timeout_ms)
+{
+	unsigned long deadline = jiffies + msecs_to_jiffies(timeout_ms);
+
+	while (READ_ONCE(current->rwsem_boost.prio) != expected &&
+	       !time_after(jiffies, deadline)) {
+		cpu_relax();
+		cond_resched();
+	}
+}
+
+static void test_basic_hold_and_release(struct kunit *test)
+{
+	struct rw_semaphore sem;
+
+	init_rwsem(&sem);
+	KUNIT_ASSERT_EQ(test, current->rwsem_boost.nr_held, 0);
+	KUNIT_ASSERT_EQ(test, rwsem_top_waiter_prio(&sem), MAX_PRIO);
+
+	down_read(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	KUNIT_EXPECT_TRUE(test, task_holds_rwsem(current, &sem));
+	up_read(&sem);
+
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+	KUNIT_EXPECT_FALSE(test, task_holds_rwsem(current, &sem));
+
+	KUNIT_ASSERT_EQ(test, down_read_trylock(&sem), 1);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	up_read(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+
+	down_write(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	KUNIT_EXPECT_TRUE(test, task_holds_rwsem(current, &sem));
+	up_write(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+
+	KUNIT_ASSERT_EQ(test, down_write_trylock(&sem), 1);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	up_write(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+
+	/* Unlock after a runtime disable must still clear the slot. */
+	down_read(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	rwsem_boost_set(false);
+	up_read(&sem);
+	rwsem_boost_set(true);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+	KUNIT_EXPECT_FALSE(test, task_holds_rwsem(current, &sem));
+}
+
+static void test_interleaved_unlock(struct kunit *test)
+{
+	struct rw_semaphore sem_a, sem_b, sem_c;
+
+	init_rwsem(&sem_a);
+	init_rwsem(&sem_b);
+	init_rwsem(&sem_c);
+
+	down_read(&sem_a);
+	down_read(&sem_b);
+	down_read(&sem_c);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 3);
+
+	/* Release out of acquisition order: B, A, C. */
+	up_read(&sem_b);
+	KUNIT_EXPECT_FALSE(test, task_holds_rwsem(current, &sem_b));
+	up_read(&sem_a);
+	KUNIT_EXPECT_FALSE(test, task_holds_rwsem(current, &sem_a));
+	up_read(&sem_c);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+}
+
+static void test_recursive_read_and_untrack(struct kunit *test)
+{
+	struct rw_semaphore sem;
+
+	init_rwsem(&sem);
+	down_read(&sem);
+	if (!down_read_trylock(&sem)) {
+		up_read(&sem);
+		KUNIT_FAIL(test, "recursive down_read_trylock failed");
+		return;
+	}
+	/* A recursive trylock gets its own slot, freed per unlock. */
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 2);
+	up_read(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	KUNIT_EXPECT_TRUE(test, task_holds_rwsem(current, &sem));
+
+	/* Untrack clears the slot before a cross-task release. */
+	rwsem_boost_untrack(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+	KUNIT_EXPECT_FALSE(test, task_holds_rwsem(current, &sem));
+	up_read(&sem);
+}
+
+static void test_overflow_graceful(struct kunit *test)
+{
+	struct rw_semaphore sems[RWSEM_SCHED_BOOST_SLOTS + 3];
+	int i;
+
+	BUILD_BUG_ON(ARRAY_SIZE(sems) > MAX_LOCKDEP_SUBCLASSES);
+	for (i = 0; i < ARRAY_SIZE(sems); i++)
+		init_rwsem(&sems[i]);
+
+	/* A subclass per lock keeps lockdep from seeing recursion. */
+	for (i = 0; i < ARRAY_SIZE(sems); i++)
+		down_read_nested(&sems[i], i);
+
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held,
+			RWSEM_SCHED_BOOST_SLOTS);
+
+	for (i = 0; i < ARRAY_SIZE(sems); i++)
+		up_read(&sems[i]);
+
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+	for (i = 0; i < ARRAY_SIZE(sems); i++)
+		KUNIT_EXPECT_FALSE(test, task_holds_rwsem(current, &sems[i]));
+}
+
+static void test_downgrade_write(struct kunit *test)
+{
+	struct rw_semaphore sem;
+
+	init_rwsem(&sem);
+	down_write(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	KUNIT_EXPECT_TRUE(test, task_holds_rwsem(current, &sem));
+
+	downgrade_write(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 1);
+	KUNIT_EXPECT_TRUE(test, task_holds_rwsem(current, &sem));
+
+	up_read(&sem);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.nr_held, 0);
+}
+
+struct boost_ctx {
+	struct rw_semaphore sem;
+	struct completion reader_locked;
+	struct completion reader_done;
+	bool holder_is_writer;
+	bool holder_is_idle;
+	bool downgrade_writer;
+	bool wait_for_contender;
+	bool saw_waiter;
+	int observed_boost_prio;
+	int observed_prio;
+	int observed_nice;
+	unsigned long base_weight;
+	unsigned long waiter_weight;
+	unsigned long observed_weight;
+	unsigned long post_unlock_weight;
+	int post_unrelated_boost_prio;
+	int post_downgrade_boost_prio;
+	int post_unlock_boost_prio;
+	int post_unlock_prio;
+};
+
+static int wakeup_holder_fn(void *arg)
+{
+	struct boost_ctx *ctx = arg;
+	struct rw_semaphore unrelated;
+
+	init_rwsem(&unrelated);
+	if (ctx->holder_is_idle) {
+		struct sched_param sp = { .sched_priority = 0 };
+
+		sched_setscheduler_nocheck(current, SCHED_IDLE, &sp);
+	} else {
+		set_user_nice(current, 19);
+	}
+	ctx->base_weight = current->se.load.weight;
+
+	if (ctx->holder_is_writer)
+		down_write(&ctx->sem);
+	else
+		down_read(&ctx->sem);
+	complete(&ctx->reader_locked);
+
+	ctx->saw_waiter = wait_for_rwsem_waiter(&ctx->sem, 500);
+	/* Sleep once so the wakeup enqueue applies any boost. */
+	usleep_range(1000, 2000);
+
+	ctx->observed_boost_prio = current->rwsem_boost.prio;
+	ctx->observed_prio = current->prio;
+	ctx->observed_nice = task_nice(current);
+	ctx->observed_weight = current->se.load.weight;
+
+	/* Cycling an unrelated rwsem must keep the boost. */
+	down_read(&unrelated);
+	up_read(&unrelated);
+	ctx->post_unrelated_boost_prio = current->rwsem_boost.prio;
+
+	if (ctx->downgrade_writer) {
+		downgrade_write(&ctx->sem);
+		ctx->post_downgrade_boost_prio = current->rwsem_boost.prio;
+		up_read(&ctx->sem);
+	} else if (ctx->holder_is_writer) {
+		up_write(&ctx->sem);
+	} else {
+		up_read(&ctx->sem);
+	}
+
+	ctx->post_unlock_boost_prio = current->rwsem_boost.prio;
+	ctx->post_unlock_prio = current->prio;
+	ctx->post_unlock_weight = current->se.load.weight;
+	complete(&ctx->reader_done);
+	return 0;
+}
+
+struct wakeup_case {
+	const char *name;
+	bool holder_is_writer;
+	bool holder_is_idle;
+	bool downgrade_writer;
+	bool waiter_is_idle;
+	int waiter_nice;
+};
+
+static const struct wakeup_case wakeup_cases[] = {
+	{ .name = "reader_holder", .waiter_nice = -10 },
+	{ .name = "writer_holder", .holder_is_writer = true,
+	  .waiter_nice = -10 },
+	{ .name = "downgrade_unboost", .holder_is_writer = true,
+	  .downgrade_writer = true, .waiter_nice = -10 },
+	{ .name = "idle_holder_cap", .holder_is_idle = true,
+	  .waiter_nice = 10 },
+	{ .name = "idle_waiter_no_boost", .waiter_is_idle = true },
+};
+
+KUNIT_ARRAY_PARAM_DESC(wakeup, wakeup_cases, name);
+
+/*
+ * A nice +19 or SCHED_IDLE holder sleeps once with a waiter queued: the
+ * wakeup must give it the waiter's weight and unlock must take it back.
+ */
+static void test_wakeup_boost(struct kunit *test)
+{
+	const struct wakeup_case *c = test->param_value;
+	struct sched_param sp = { .sched_priority = 0 };
+	unsigned long exp_weight;
+	struct task_struct *holder;
+	struct boost_ctx *ctx;
+	int exp_boost, exp_prio;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->holder_is_writer = c->holder_is_writer;
+	ctx->holder_is_idle = c->holder_is_idle;
+	ctx->downgrade_writer = c->downgrade_writer;
+	init_rwsem(&ctx->sem);
+	init_completion(&ctx->reader_locked);
+	init_completion(&ctx->reader_done);
+
+	holder = kthread_run(wakeup_holder_fn, ctx, "rwsem_hld");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, holder);
+
+	wait_for_completion(&ctx->reader_locked);
+	/* Each case runs in a new KUnit thread: nothing to restore. */
+	if (c->waiter_is_idle)
+		sched_setscheduler_nocheck(current, SCHED_IDLE, &sp);
+	else
+		set_user_nice(current, c->waiter_nice);
+	/* A boosted holder runs with exactly the waiter's weight. */
+	ctx->waiter_weight = current->se.load.weight;
+	if (c->holder_is_writer) {
+		down_read(&ctx->sem);
+		up_read(&ctx->sem);
+	} else {
+		down_write(&ctx->sem);
+		up_write(&ctx->sem);
+	}
+	wait_for_completion(&ctx->reader_done);
+
+	exp_prio = c->holder_is_idle ? DEFAULT_PRIO : NICE_TO_PRIO(19);
+	exp_boost = NICE_TO_PRIO(c->waiter_nice);
+	exp_weight = ctx->waiter_weight;
+	if (c->waiter_is_idle) {
+		/* A SCHED_IDLE waiter asks for no boost. */
+		exp_boost = MAX_PRIO;
+		exp_weight = ctx->base_weight;
+	}
+
+	KUNIT_EXPECT_TRUE(test, ctx->saw_waiter);
+	KUNIT_EXPECT_EQ(test, ctx->observed_boost_prio, exp_boost);
+	KUNIT_EXPECT_EQ(test, ctx->post_unrelated_boost_prio, exp_boost);
+	KUNIT_EXPECT_EQ(test, ctx->observed_weight, exp_weight);
+	/* p->prio and user-visible nice must remain untouched. */
+	KUNIT_EXPECT_EQ(test, ctx->observed_prio, exp_prio);
+	KUNIT_EXPECT_EQ(test, ctx->observed_nice, c->holder_is_idle ? 0 : 19);
+	if (c->downgrade_writer)
+		KUNIT_EXPECT_EQ(test, ctx->post_downgrade_boost_prio, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, ctx->post_unlock_boost_prio, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, ctx->post_unlock_prio, exp_prio);
+	KUNIT_EXPECT_EQ(test, ctx->post_unlock_weight, ctx->base_weight);
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&ctx->sem), MAX_PRIO);
+	KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&ctx->sem));
+}
+
+struct packing_waiter {
+	struct rw_semaphore *sem;
+	int nice;
+	bool is_writer;
+	int prio_after_lock;
+	struct completion ready;
+	struct completion done;
+};
+
+static int packing_waiter_fn(void *arg)
+{
+	struct packing_waiter *w = arg;
+
+	set_user_nice(current, w->nice);
+	complete(&w->ready);
+	if (w->is_writer) {
+		down_write(w->sem);
+		w->prio_after_lock = rwsem_top_waiter_prio(w->sem);
+		up_write(w->sem);
+	} else {
+		down_read(w->sem);
+		w->prio_after_lock = rwsem_top_waiter_prio(w->sem);
+		up_read(w->sem);
+	}
+	complete(&w->done);
+	return 0;
+}
+
+/*
+ * Verify the packed waiter priority at the nice +19 and -20 limits, as
+ * writers queue and take the lock, and when downgrade_write() wakes a
+ * reader; sem->count must be clean after the last unlock.
+ */
+static void test_waiter_prio_packing(struct kunit *test)
+{
+	struct rw_semaphore sem;
+	struct packing_waiter wa = { .sem = &sem, .nice = 19, .is_writer = true };
+	struct packing_waiter wb = { .sem = &sem, .nice = -20, .is_writer = true };
+	struct packing_waiter rc = { .sem = &sem, .nice = -15, .is_writer = false };
+	struct packing_waiter wd = { .sem = &sem, .nice = -5, .is_writer = true };
+	struct packing_waiter we = { .sem = &sem, .nice = -10, .is_writer = true };
+	struct task_struct *ta, *tb, *tc, *td, *te;
+	bool a_first, b_first;
+
+	init_rwsem(&sem);
+	init_completion(&wa.ready);
+	init_completion(&wa.done);
+	init_completion(&wb.ready);
+	init_completion(&wb.done);
+	init_completion(&rc.ready);
+	init_completion(&rc.done);
+	init_completion(&wd.ready);
+	init_completion(&wd.done);
+	init_completion(&we.ready);
+	init_completion(&we.done);
+
+	/* Part 1: nice 19 and -20 encodings, multi-writer upgrade. */
+	down_read(&sem);
+	ta = kthread_run(packing_waiter_fn, &wa, "rwsem_pack_wa");
+	if (IS_ERR(ta)) {
+		up_read(&sem);
+		KUNIT_FAIL(test, "failed to start writer A");
+		return;
+	}
+	wait_for_completion(&wa.ready);
+	KUNIT_EXPECT_TRUE(test, wait_for_waiter_prio(&sem, NICE_TO_PRIO(19), 500));
+
+	tb = kthread_run(packing_waiter_fn, &wb, "rwsem_pack_wb");
+	if (IS_ERR(tb)) {
+		up_read(&sem);
+		wait_for_completion(&wa.done);
+		KUNIT_FAIL(test, "failed to start writer B");
+		return;
+	}
+	wait_for_completion(&wb.ready);
+	KUNIT_EXPECT_TRUE(test, wait_for_waiter_prio(&sem, NICE_TO_PRIO(-20), 500));
+
+	up_read(&sem);
+	wait_for_completion(&wa.done);
+	wait_for_completion(&wb.done);
+
+	/* The first writer sees the other; the last clears the prio. */
+	a_first = wa.prio_after_lock == NICE_TO_PRIO(-20) &&
+		  wb.prio_after_lock == MAX_PRIO;
+	b_first = wb.prio_after_lock == NICE_TO_PRIO(19) &&
+		  wa.prio_after_lock == MAX_PRIO;
+	KUNIT_EXPECT_TRUE(test, a_first || b_first);
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), MAX_PRIO);
+	KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&sem));
+	KUNIT_ASSERT_EQ(test, down_write_trylock(&sem), 1);
+
+	/* Part 2: downgrade_write() wakes C; prio falls to writer D. */
+	tc = kthread_run(packing_waiter_fn, &rc, "rwsem_pack_rc");
+	if (IS_ERR(tc)) {
+		up_write(&sem);
+		KUNIT_FAIL(test, "failed to start reader C");
+		return;
+	}
+	wait_for_completion(&rc.ready);
+	KUNIT_EXPECT_TRUE(test, wait_for_waiter_prio(&sem, NICE_TO_PRIO(-15), 500));
+
+	td = kthread_run(packing_waiter_fn, &wd, "rwsem_pack_wd");
+	if (IS_ERR(td)) {
+		up_write(&sem);
+		wait_for_completion(&rc.done);
+		KUNIT_FAIL(test, "failed to start writer D");
+		return;
+	}
+	wait_for_completion(&wd.ready);
+	KUNIT_EXPECT_TRUE(test, wait_for_task_sleep(td, 500));
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), NICE_TO_PRIO(-15));
+
+	downgrade_write(&sem);
+	wait_for_completion(&rc.done);
+	KUNIT_EXPECT_EQ(test, rc.prio_after_lock, NICE_TO_PRIO(-5));
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), NICE_TO_PRIO(-5));
+
+	up_read(&sem);
+	wait_for_completion(&wd.done);
+	KUNIT_EXPECT_EQ(test, wd.prio_after_lock, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), MAX_PRIO);
+	KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&sem));
+	KUNIT_ASSERT_EQ(test, down_write_trylock(&sem), 1);
+	up_write(&sem);
+
+	/* Part 3: runtime disable still clears queued prio bits. */
+	down_read(&sem);
+	te = kthread_run(packing_waiter_fn, &we, "rwsem_pack_we");
+	if (IS_ERR(te)) {
+		up_read(&sem);
+		KUNIT_FAIL(test, "failed to start writer E");
+		return;
+	}
+	wait_for_completion(&we.ready);
+	KUNIT_EXPECT_TRUE(test,
+			  wait_for_waiter_prio(&sem, NICE_TO_PRIO(-10), 500));
+
+	rwsem_boost_set(false);
+	up_read(&sem);
+	wait_for_completion(&we.done);
+	rwsem_boost_set(true);
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), MAX_PRIO);
+	KUNIT_EXPECT_FALSE(test, rwsem_is_locked(&sem));
+}
+
+struct queued_reader {
+	struct rw_semaphore *sem;
+	int nice;
+	int ret;
+	u8 nr_held_after;
+	int boost_after;
+	struct completion done;
+};
+
+static int queued_reader_fn(void *arg)
+{
+	struct queued_reader *r = arg;
+
+	allow_signal(SIGKILL);
+	set_user_nice(current, r->nice);
+	r->ret = down_read_killable(r->sem);
+	if (r->ret == 0)
+		up_read(r->sem);
+	r->nr_held_after = current->rwsem_boost.nr_held;
+	r->boost_after = current->rwsem_boost.prio;
+	complete(&r->done);
+	return 0;
+}
+
+/*
+ * rwsem_mark_wake() grants the lock to queued readers before they run,
+ * so a queued reader must already own its slot.  A killed reader must
+ * drop the slot and any boost its wakeup took from it, and the top
+ * waiter leaving must republish the next priority.
+ */
+static void test_queued_reader_slot(struct kunit *test)
+{
+	struct rw_semaphore sem;
+	struct queued_reader low = { .sem = &sem, .nice = 0 };
+	struct queued_reader top = { .sem = &sem, .nice = -10 };
+	struct packing_waiter w = { .sem = &sem, .nice = 5, .is_writer = true };
+	struct task_struct *lt, *tt, *wt;
+
+	init_rwsem(&sem);
+	init_completion(&low.done);
+	init_completion(&top.done);
+	init_completion(&w.ready);
+	init_completion(&w.done);
+
+	down_write(&sem);
+	lt = kthread_run(queued_reader_fn, &low, "rwsem_q_low");
+	if (IS_ERR(lt)) {
+		up_write(&sem);
+		KUNIT_FAIL(test, "kthread_run failed");
+		return;
+	}
+	KUNIT_EXPECT_TRUE(test, wait_for_waiter_prio(&sem, NICE_TO_PRIO(0),
+						     500));
+	tt = kthread_run(queued_reader_fn, &top, "rwsem_q_top");
+	if (IS_ERR(tt)) {
+		up_write(&sem);
+		wait_for_completion(&low.done);
+		KUNIT_FAIL(test, "kthread_run failed");
+		return;
+	}
+	KUNIT_EXPECT_TRUE(test, wait_for_waiter_prio(&sem, NICE_TO_PRIO(-10),
+						     500));
+	KUNIT_EXPECT_TRUE(test, task_holds_rwsem(lt, &sem));
+	KUNIT_EXPECT_TRUE(test, task_holds_rwsem(tt, &sem));
+
+	wt = kthread_run(packing_waiter_fn, &w, "rwsem_q_wr");
+	if (IS_ERR(wt)) {
+		up_write(&sem);
+		wait_for_completion(&low.done);
+		wait_for_completion(&top.done);
+		KUNIT_FAIL(test, "kthread_run failed");
+		return;
+	}
+	wait_for_completion(&w.ready);
+	KUNIT_EXPECT_TRUE(test, wait_for_task_sleep(wt, 500));
+
+	/* The kill wakeup boosts the low reader through its slot. */
+	send_sig(SIGKILL, lt, 1);
+	wait_for_completion(&low.done);
+	KUNIT_EXPECT_EQ(test, low.ret, -EINTR);
+	KUNIT_EXPECT_EQ(test, low.nr_held_after, 0);
+	KUNIT_EXPECT_EQ(test, low.boost_after, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), NICE_TO_PRIO(-10));
+
+	/* Kill the top waiter: the writer behind it becomes the top. */
+	send_sig(SIGKILL, tt, 1);
+	wait_for_completion(&top.done);
+	KUNIT_EXPECT_EQ(test, top.ret, -EINTR);
+	KUNIT_EXPECT_EQ(test, top.nr_held_after, 0);
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), NICE_TO_PRIO(5));
+
+	up_write(&sem);
+	wait_for_completion(&w.done);
+	KUNIT_EXPECT_EQ(test, rwsem_top_waiter_prio(&sem), MAX_PRIO);
+}
+
+static int hog_fn(void *arg)
+{
+	set_user_nice(current, (long)arg);
+	while (!kthread_should_stop()) {
+		cpu_relax();
+		cond_resched();
+	}
+	return 0;
+}
+
+static int busy_reader_fn(void *arg)
+{
+	struct boost_ctx *ctx = arg;
+	int i;
+
+	set_user_nice(current, 19);
+	ctx->base_weight = current->se.load.weight;
+	down_read(&ctx->sem);
+	complete(&ctx->reader_locked);
+
+	if (ctx->wait_for_contender)
+		ctx->saw_waiter = wait_for_rwsem_waiter(&ctx->sem, 500);
+
+	/*
+	 * Spin 20 rounds of 500 us (wall clock) against nice 0 hogs.
+	 * Once the nice -10 writer queues, the tick or preemption boosts
+	 * this reader to the writer's weight.
+	 */
+	for (i = 0; i < 20; i++) {
+		u64 t0 = ktime_get_ns();
+
+		while (ktime_get_ns() - t0 < 500 * NSEC_PER_USEC)
+			cpu_relax();
+		cond_resched();
+	}
+
+	ctx->observed_boost_prio = current->rwsem_boost.prio;
+	ctx->observed_prio = current->prio;
+	ctx->observed_nice = task_nice(current);
+	ctx->observed_weight = current->se.load.weight;
+
+	up_read(&ctx->sem);
+	ctx->post_unlock_boost_prio = current->rwsem_boost.prio;
+	ctx->post_unlock_prio = current->prio;
+	ctx->post_unlock_weight = current->se.load.weight;
+	complete(&ctx->reader_done);
+	return 0;
+}
+
+KUNIT_DEFINE_ACTION_WRAPPER(stop_hog_action, kthread_stop,
+			    struct task_struct *);
+
+static struct task_struct *start_pinned_hog(struct kunit *test, int cpu,
+					    int nice)
+{
+	struct task_struct *hog;
+	int err;
+
+	hog = kthread_run_on_cpu(hog_fn, (void *)(long)nice, cpu,
+				 "rwsem_hog/%u");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, hog);
+	err = kunit_add_action_or_reset(test, stop_hog_action, hog);
+	KUNIT_ASSERT_EQ(test, err, 0);
+	return hog;
+}
+
+static void start_pinned_hogs(struct kunit *test, int count, int cpu,
+			      int nice)
+{
+	int i;
+
+	for (i = 0; i < count; i++)
+		start_pinned_hog(test, cpu, nice);
+}
+
+static u64 run_one_inversion_iter(struct kunit *test, struct boost_ctx *ctx,
+				  int cpu)
+{
+	struct task_struct *reader;
+	int saved_nice = task_nice(current);
+	u64 wait_ns;
+
+	reinit_completion(&ctx->reader_locked);
+	reinit_completion(&ctx->reader_done);
+
+	reader = kthread_run_on_cpu(busy_reader_fn, ctx, cpu, "rwsem_rdr/%u");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, reader);
+
+	wait_for_completion(&ctx->reader_locked);
+	set_user_nice(current, -10);
+	ctx->waiter_weight = current->se.load.weight;
+	wait_ns = ktime_get_ns();
+	down_write(&ctx->sem);
+	wait_ns = ktime_get_ns() - wait_ns;
+	up_write(&ctx->sem);
+	set_user_nice(current, saved_nice);
+
+	wait_for_completion(&ctx->reader_done);
+	return wait_ns;
+}
+
+static void test_preemption_inversion_latency(struct kunit *test)
+{
+	struct boost_ctx *ctx;
+	const int iters = 3;
+	int cpu = cpumask_first(cpu_online_mask);
+	u64 ctrl_sum = 0, treat_sum = 0;
+	u64 ctrl_max = 0, treat_max = 0;
+	int i;
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	ctx->wait_for_contender = true;
+	init_rwsem(&ctx->sem);
+	init_completion(&ctx->reader_locked);
+	init_completion(&ctx->reader_done);
+
+	start_pinned_hogs(test, 4, cpu, 0);
+
+	rwsem_boost_set(false);
+	for (i = 0; i < iters; i++) {
+		u64 w = run_one_inversion_iter(test, ctx, cpu);
+
+		ctrl_sum += w;
+		ctrl_max = max(ctrl_max, w);
+		KUNIT_EXPECT_TRUE(test, ctx->saw_waiter);
+		KUNIT_EXPECT_EQ(test, ctx->observed_boost_prio, MAX_PRIO);
+		KUNIT_EXPECT_EQ(test, ctx->observed_weight, ctx->base_weight);
+	}
+
+	rwsem_boost_set(true);
+	for (i = 0; i < iters; i++) {
+		u64 w = run_one_inversion_iter(test, ctx, cpu);
+
+		treat_sum += w;
+		treat_max = max(treat_max, w);
+		KUNIT_EXPECT_TRUE(test, ctx->saw_waiter);
+		KUNIT_EXPECT_EQ(test, ctx->observed_boost_prio,
+				NICE_TO_PRIO(-10));
+		KUNIT_EXPECT_EQ(test, ctx->observed_weight, ctx->waiter_weight);
+		KUNIT_EXPECT_EQ(test, ctx->observed_prio, NICE_TO_PRIO(19));
+		KUNIT_EXPECT_EQ(test, ctx->post_unlock_boost_prio, MAX_PRIO);
+		KUNIT_EXPECT_EQ(test, ctx->post_unlock_weight, ctx->base_weight);
+	}
+
+	kunit_info(test,
+		   "A/B (n=%d, 4 hogs on cpu%d): Control mean=%llu ms max=%llu ms | Treatment mean=%llu ms max=%llu ms\n",
+		   iters, cpu,
+		   div_u64(div_u64(ctrl_sum, iters), NSEC_PER_MSEC),
+		   div_u64(ctrl_max, NSEC_PER_MSEC),
+		   div_u64(div_u64(treat_sum, iters), NSEC_PER_MSEC),
+		   div_u64(treat_max, NSEC_PER_MSEC));
+
+	KUNIT_EXPECT_LT(test, treat_sum, ctrl_sum);
+}
+
+static void test_no_boost_uncontended(struct kunit *test)
+{
+	struct boost_ctx *ctx;
+	struct task_struct *reader;
+	int cpu = cpumask_first(cpu_online_mask);
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, ctx);
+	init_rwsem(&ctx->sem);
+	init_completion(&ctx->reader_locked);
+	init_completion(&ctx->reader_done);
+
+	start_pinned_hogs(test, 2, cpu, 0);
+
+	reader = kthread_run_on_cpu(busy_reader_fn, ctx, cpu, "rwsem_rdr/%u");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, reader);
+
+	wait_for_completion(&ctx->reader_locked);
+	/* No waiter blocks on ctx->sem. */
+	wait_for_completion(&ctx->reader_done);
+
+	KUNIT_EXPECT_EQ(test, ctx->observed_boost_prio, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, ctx->observed_prio, NICE_TO_PRIO(19));
+	KUNIT_EXPECT_EQ(test, ctx->observed_nice, 19);
+	KUNIT_EXPECT_EQ(test, ctx->observed_weight, ctx->base_weight);
+}
+
+static noinline u64 bench_read_fastpath(struct rw_semaphore *sem, int iters)
+{
+	u64 start = ktime_get_ns();
+	int i;
+
+	for (i = 0; i < iters; i++) {
+		down_read(sem);
+		barrier();
+		up_read(sem);
+	}
+	return ktime_get_ns() - start;
+}
+
+static noinline u64 bench_write_fastpath(struct rw_semaphore *sem, int iters)
+{
+	u64 start = ktime_get_ns();
+	int i;
+
+	for (i = 0; i < iters; i++) {
+		down_write(sem);
+		barrier();
+		up_write(sem);
+	}
+	return ktime_get_ns() - start;
+}
+
+static void format_ns_per_op(u64 total_ns, u32 total_ops, u64 *whole, u32 *frac)
+{
+	u32 rem;
+
+	*whole = div_u64_rem(total_ns, total_ops, &rem);
+	*frac = div_u64((u64)rem * 100, total_ops);
+}
+
+/*
+ * Time read lock/unlock of @sem while current holds @src for read and
+ * is boosted by a nice -10 writer queued on @src.
+ */
+static u64 bench_boosted_read(struct kunit *test, struct rw_semaphore *src,
+			      struct rw_semaphore *sem, int iters)
+{
+	struct packing_waiter w = {
+		.sem = src,
+		.nice = -10,
+		.is_writer = true,
+	};
+	struct task_struct *t;
+	u64 ns;
+
+	init_completion(&w.ready);
+	init_completion(&w.done);
+	down_read(src);
+	t = kthread_run(packing_waiter_fn, &w, "rwsem_bench_wr");
+	if (IS_ERR(t)) {
+		up_read(src);
+		KUNIT_FAIL(test, "failed to start the boosting writer");
+		return 0;
+	}
+	wait_for_completion(&w.ready);
+	KUNIT_EXPECT_TRUE(test, wait_for_rwsem_waiter(src, 500));
+	/* Sleep once so the wakeup enqueue applies the boost. */
+	usleep_range(1000, 2000);
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.prio, NICE_TO_PRIO(-10));
+
+	ns = bench_read_fastpath(sem, iters);
+
+	KUNIT_EXPECT_EQ(test, current->rwsem_boost.prio, NICE_TO_PRIO(-10));
+	up_read(src);
+	wait_for_completion(&w.done);
+	return ns;
+}
+
+static void test_fastpath_overhead(struct kunit *test)
+{
+	struct rw_semaphore outer1, outer2, sem, src;
+	const int rounds = 5;
+	const int per_round = 200000;
+	const u32 total_ops = rounds * per_round;
+	u64 r_off = 0, r_on = 0, w_off = 0, w_on = 0, n_off = 0, n_on = 0;
+	u64 b_on;
+	u64 r0, r1, w0, w1, n0, n1, b1;
+	u32 rf0, rf1, wf0, wf1, nf0, nf1, bf1;
+	int i;
+
+	if (!benchmark)
+		kunit_skip(test, "needs rwsem_sched_boost_test.benchmark=1");
+
+	init_rwsem(&outer1);
+	init_rwsem(&outer2);
+	init_rwsem(&sem);
+	init_rwsem(&src);
+
+	/* Warmup instruction and branch caches. */
+	bench_read_fastpath(&sem, 10000);
+	bench_write_fastpath(&sem, 10000);
+
+	for (i = 0; i < rounds; i++) {
+		rwsem_boost_set(false);
+		r_off += bench_read_fastpath(&sem, per_round);
+		w_off += bench_write_fastpath(&sem, per_round);
+
+		rwsem_boost_set(true);
+		r_on += bench_read_fastpath(&sem, per_round);
+		w_on += bench_write_fastpath(&sem, per_round);
+	}
+
+	/* Nested read fastpath with two outer slots already in use. */
+	for (i = 0; i < rounds; i++) {
+		rwsem_boost_set(false);
+		down_read(&outer1);
+		down_read(&outer2);
+		n_off += bench_read_fastpath(&sem, per_round);
+		up_read(&outer2);
+		up_read(&outer1);
+
+		rwsem_boost_set(true);
+		down_read(&outer1);
+		down_read(&outer2);
+		n_on += bench_read_fastpath(&sem, per_round);
+		up_read(&outer2);
+		up_read(&outer1);
+	}
+
+	/* Boosted holder cycling an unrelated, uncontended rwsem. */
+	rwsem_boost_set(true);
+	b_on = bench_boosted_read(test, &src, &sem, total_ops);
+
+	format_ns_per_op(r_off, total_ops, &r0, &rf0);
+	format_ns_per_op(r_on, total_ops, &r1, &rf1);
+	format_ns_per_op(w_off, total_ops, &w0, &wf0);
+	format_ns_per_op(w_on, total_ops, &w1, &wf1);
+	format_ns_per_op(n_off, total_ops, &n0, &nf0);
+	format_ns_per_op(n_on, total_ops, &n1, &nf1);
+	format_ns_per_op(b_on, total_ops, &b1, &bf1);
+
+	kunit_info(test,
+		   "Fastpath (%u ops): read off=%llu.%02u on=%llu.%02u ns/op | write off=%llu.%02u on=%llu.%02u ns/op | nested2 read off=%llu.%02u on=%llu.%02u ns/op | boosted read on=%llu.%02u ns/op\n",
+		   total_ops,
+		   r0, rf0, r1, rf1,
+		   w0, wf0, w1, wf1,
+		   n0, nf0, n1, nf1,
+		   b1, bf1);
+}
+
+struct renice_ctx {
+	struct rw_semaphore sem;
+	struct completion locked;
+	struct completion done;
+	bool saw_waiter;
+	unsigned long w_boosted;
+	unsigned long w_after_nice;
+	unsigned long w_after_unlock;
+	int prio_boosted;
+	int prio_after_nice;
+	int prio_after_unlock;
+};
+
+static int renice_holder_fn(void *arg)
+{
+	struct renice_ctx *c = arg;
+
+	set_user_nice(current, 19);
+	down_read(&c->sem);
+	complete(&c->locked);
+	c->saw_waiter = wait_for_rwsem_waiter(&c->sem, 500);
+	usleep_range(1000, 2000);
+	c->w_boosted = current->se.load.weight;
+	c->prio_boosted = current->rwsem_boost.prio;
+	/* Own priority now outranks the nice -10 boost. */
+	set_user_nice(current, -15);
+	c->w_after_nice = current->se.load.weight;
+	c->prio_after_nice = current->rwsem_boost.prio;
+	up_read(&c->sem);
+	c->w_after_unlock = current->se.load.weight;
+	c->prio_after_unlock = current->rwsem_boost.prio;
+	complete(&c->done);
+	return 0;
+}
+
+static void test_renice_boosted_holder(struct kunit *test)
+{
+	unsigned long w10, w15;
+	struct task_struct *t;
+	struct renice_ctx *c;
+
+	c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, c);
+	init_rwsem(&c->sem);
+	init_completion(&c->locked);
+	init_completion(&c->done);
+
+	set_user_nice(current, -15);
+	w15 = current->se.load.weight;
+	set_user_nice(current, -10);
+	w10 = current->se.load.weight;
+
+	t = kthread_run(renice_holder_fn, c, "rwsem_renice_hld");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t);
+	wait_for_completion(&c->locked);
+	down_write(&c->sem);
+	up_write(&c->sem);
+	wait_for_completion(&c->done);
+
+	KUNIT_EXPECT_TRUE(test, c->saw_waiter);
+	KUNIT_EXPECT_EQ(test, c->prio_boosted, NICE_TO_PRIO(-10));
+	KUNIT_EXPECT_EQ(test, c->w_boosted, w10);
+	KUNIT_EXPECT_EQ(test, c->prio_after_nice, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, c->w_after_nice, w15);
+	KUNIT_EXPECT_EQ(test, c->w_after_unlock, w15);
+	KUNIT_EXPECT_EQ(test, c->prio_after_unlock, MAX_PRIO);
+}
+
+struct class_switch_ctx {
+	struct rw_semaphore sem;
+	struct completion locked;
+	struct completion done;
+	bool saw_waiter;
+	bool unlinked_in_rt;
+	int rt_err;
+	int fair_err;
+	int prio_boosted;
+	int prio_in_rt;
+	int prio_reboosted;
+	int prio_after_unlock;
+	unsigned long base_weight;
+	unsigned long w_boosted;
+	unsigned long w_in_rt;
+	unsigned long w_reboosted;
+	unsigned long w_after_unlock;
+};
+
+static int class_switch_holder_fn(void *arg)
+{
+	struct sched_param fair_sp = { .sched_priority = 0 };
+	struct sched_param rt_sp = { .sched_priority = 1 };
+	struct class_switch_ctx *c = arg;
+
+	set_user_nice(current, 19);
+	c->base_weight = current->se.load.weight;
+	down_read(&c->sem);
+	complete(&c->locked);
+	c->saw_waiter = wait_for_rwsem_waiter(&c->sem, 500);
+	usleep_range(1000, 2000);
+	c->prio_boosted = current->rwsem_boost.prio;
+	c->w_boosted = current->se.load.weight;
+
+	/* Leaving fair clears the boost and unlinks rq_node. */
+	c->rt_err = sched_setscheduler_nocheck(current, SCHED_FIFO, &rt_sp);
+	c->prio_in_rt = current->rwsem_boost.prio;
+	c->w_in_rt = current->se.load.weight;
+	c->unlinked_in_rt = list_empty(&current->rwsem_boost.rq_node);
+
+	/* Returning via ENQUEUE_CLASS re-boosts on the next tick. */
+	c->fair_err = sched_setscheduler_nocheck(current, SCHED_NORMAL,
+						 &fair_sp);
+	spin_wait_boost_prio(NICE_TO_PRIO(-10), 500);
+	c->prio_reboosted = current->rwsem_boost.prio;
+	c->w_reboosted = current->se.load.weight;
+
+	up_read(&c->sem);
+	c->prio_after_unlock = current->rwsem_boost.prio;
+	c->w_after_unlock = current->se.load.weight;
+	complete(&c->done);
+	return 0;
+}
+
+static void test_class_switch_clears_and_reboosts(struct kunit *test)
+{
+	struct class_switch_ctx *c;
+	struct task_struct *t;
+	unsigned long w10;
+
+	c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, c);
+	init_rwsem(&c->sem);
+	init_completion(&c->locked);
+	init_completion(&c->done);
+
+	set_user_nice(current, -10);
+	w10 = current->se.load.weight;
+
+	t = kthread_run(class_switch_holder_fn, c, "rwsem_cls_hld");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, t);
+	wait_for_completion(&c->locked);
+	down_write(&c->sem);
+	up_write(&c->sem);
+	wait_for_completion(&c->done);
+
+	KUNIT_EXPECT_TRUE(test, c->saw_waiter);
+	KUNIT_EXPECT_EQ(test, c->prio_boosted, NICE_TO_PRIO(-10));
+	KUNIT_EXPECT_EQ(test, c->w_boosted, w10);
+	KUNIT_EXPECT_EQ(test, c->rt_err, 0);
+	KUNIT_EXPECT_EQ(test, c->prio_in_rt, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, c->w_in_rt, c->base_weight);
+	KUNIT_EXPECT_TRUE(test, c->unlinked_in_rt);
+	KUNIT_EXPECT_EQ(test, c->fair_err, 0);
+	KUNIT_EXPECT_EQ(test, c->prio_reboosted, NICE_TO_PRIO(-10));
+	KUNIT_EXPECT_EQ(test, c->w_reboosted, w10);
+	KUNIT_EXPECT_EQ(test, c->prio_after_unlock, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, c->w_after_unlock, c->base_weight);
+}
+
+struct chain_ctx {
+	struct rw_semaphore sem1;
+	struct rw_semaphore sem2;
+	struct completion a_locked;
+	struct completion b_locked;
+	struct completion a_done;
+	struct completion b_done;
+	bool a_saw_prio;
+	bool b_saw_waiter;
+	int b_boost_before;
+	int a_sem1_prio;
+	int a_boost;
+	int a_prio;
+	int a_post_boost;
+	int b_post_boost;
+	unsigned long a_base_weight;
+	unsigned long a_weight;
+	unsigned long a_post_weight;
+};
+
+static int chain_a_fn(void *arg)
+{
+	struct chain_ctx *c = arg;
+
+	set_user_nice(current, 19);
+	c->a_base_weight = current->se.load.weight;
+	down_read(&c->sem1);
+	complete(&c->a_locked);
+	c->a_saw_prio = wait_for_waiter_prio(&c->sem1, NICE_TO_PRIO(-10), 500);
+	usleep_range(1000, 2000);
+	c->a_sem1_prio = rwsem_top_waiter_prio(&c->sem1);
+	c->a_boost = current->rwsem_boost.prio;
+	c->a_weight = current->se.load.weight;
+	c->a_prio = current->prio;
+	up_read(&c->sem1);
+	c->a_post_boost = current->rwsem_boost.prio;
+	c->a_post_weight = current->se.load.weight;
+	complete(&c->a_done);
+	return 0;
+}
+
+static int chain_b_fn(void *arg)
+{
+	struct chain_ctx *c = arg;
+
+	set_user_nice(current, 19);
+	down_read(&c->sem2);
+	complete(&c->b_locked);
+	c->b_saw_waiter = wait_for_rwsem_waiter(&c->sem2, 500);
+	/* Sleep once so the wakeup boosts B before it queues. */
+	usleep_range(1000, 2000);
+	c->b_boost_before = current->rwsem_boost.prio;
+	down_write(&c->sem1);
+	up_write(&c->sem1);
+	up_read(&c->sem2);
+	c->b_post_boost = current->rwsem_boost.prio;
+	complete(&c->b_done);
+	return 0;
+}
+
+/*
+ * Transitive boost across two rwsems: nice +19 A holds sem1, nice +19 B
+ * holds sem2 while boosted by nice -10 C, then B blocks on sem1 and
+ * propagates its boost to A.
+ */
+static void test_transitive_boost_chain(struct kunit *test)
+{
+	struct task_struct *ta, *tb;
+	struct chain_ctx *c;
+	unsigned long w10;
+
+	c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, c);
+	init_rwsem(&c->sem1);
+	init_rwsem(&c->sem2);
+	init_completion(&c->a_locked);
+	init_completion(&c->b_locked);
+	init_completion(&c->a_done);
+	init_completion(&c->b_done);
+
+	set_user_nice(current, -10);
+	w10 = current->se.load.weight;
+
+	ta = kthread_run(chain_a_fn, c, "rwsem_chain_a");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ta);
+	wait_for_completion(&c->a_locked);
+
+	tb = kthread_run(chain_b_fn, c, "rwsem_chain_b");
+	if (IS_ERR(tb)) {
+		wait_for_completion(&c->a_done);
+		KUNIT_FAIL(test, "failed to start chain B");
+		return;
+	}
+	wait_for_completion(&c->b_locked);
+
+	down_write(&c->sem2);
+	up_write(&c->sem2);
+	wait_for_completion(&c->a_done);
+	wait_for_completion(&c->b_done);
+
+	KUNIT_EXPECT_TRUE(test, c->b_saw_waiter);
+	KUNIT_EXPECT_EQ(test, c->b_boost_before, NICE_TO_PRIO(-10));
+	KUNIT_EXPECT_TRUE(test, c->a_saw_prio);
+	KUNIT_EXPECT_EQ(test, c->a_sem1_prio, NICE_TO_PRIO(-10));
+	KUNIT_EXPECT_EQ(test, c->a_boost, NICE_TO_PRIO(-10));
+	KUNIT_EXPECT_EQ(test, c->a_weight, w10);
+	KUNIT_EXPECT_EQ(test, c->a_prio, NICE_TO_PRIO(19));
+	KUNIT_EXPECT_EQ(test, c->a_post_boost, MAX_PRIO);
+	KUNIT_EXPECT_EQ(test, c->a_post_weight, c->a_base_weight);
+	KUNIT_EXPECT_EQ(test, c->b_post_boost, MAX_PRIO);
+}
+
+struct pelt_ctx {
+	struct rw_semaphore sem;
+	struct completion locked;
+	struct completion done;
+	atomic_t stop;
+};
+
+static int pelt_holder_fn(void *arg)
+{
+	struct pelt_ctx *c = arg;
+
+	set_user_nice(current, 19);
+	down_read(&c->sem);
+	complete(&c->locked);
+	while (!atomic_read(&c->stop)) {
+		cpu_relax();
+		cond_resched();
+	}
+	up_read(&c->sem);
+	complete(&c->done);
+	return 0;
+}
+
+static void stop_pelt_holder_action(void *data)
+{
+	struct pelt_ctx *c = data;
+
+	atomic_set(&c->stop, 1);
+	wait_for_completion(&c->done);
+}
+
+/*
+ * A queued holder kept off-CPU by a higher-priority hog (nice -17)
+ * lags behind cfs_rq PELT.  When a nice 0 writer arrives and the
+ * tick boosts the holder without running it (hog still holds a
+ * ~45:1 weight advantage over the boosted holder), reweighting must
+ * sync se.avg.last_update_time before reweight_entity().
+ */
+static void test_reweight_updates_pelt(struct kunit *test)
+{
+	struct task_struct *hog, *holder, *writer;
+	int cpu = cpumask_first(cpu_online_mask);
+	struct packing_waiter w = { .nice = 0, .is_writer = true };
+	u64 exec_before, exec_after, pelt_before, pelt_after;
+	struct pelt_ctx *c;
+	int err;
+
+	c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, c);
+	init_rwsem(&c->sem);
+	init_completion(&c->locked);
+	init_completion(&c->done);
+	w.sem = &c->sem;
+	init_completion(&w.ready);
+	init_completion(&w.done);
+
+	/* Stay above the nice -17 hog so the test runs freely. */
+	set_user_nice(current, -20);
+
+	/*
+	 * Register holder cleanup before starting the hog so KUnit's
+	 * LIFO teardown always stops the hog first, then the holder.
+	 */
+	holder = kthread_run_on_cpu(pelt_holder_fn, c, cpu, "rwsem_ph/%u");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, holder);
+	err = kunit_add_action_or_reset(test, stop_pelt_holder_action, c);
+	KUNIT_ASSERT_EQ(test, err, 0);
+	wait_for_completion(&c->locked);
+
+	hog = start_pinned_hog(test, cpu, -17);
+
+	/* Let the hog preempt the holder and advance PELT. */
+	msleep(20);
+	exec_before = READ_ONCE(holder->se.sum_exec_runtime);
+	pelt_before = READ_ONCE(holder->se.avg.last_update_time);
+	msleep(30);
+
+	writer = kthread_run(packing_waiter_fn, &w, "rwsem_pwr");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, writer);
+	wait_for_completion(&w.ready);
+	KUNIT_EXPECT_TRUE(test,
+			  poll_until(READ_ONCE(holder->rwsem_boost.prio) ==
+				     NICE_TO_PRIO(0), 2000));
+
+	exec_after = READ_ONCE(holder->se.sum_exec_runtime);
+	pelt_after = READ_ONCE(holder->se.avg.last_update_time);
+
+	kunit_release_action(test, stop_hog_action, hog);
+	kunit_release_action(test, stop_pelt_holder_action, c);
+	wait_for_completion(&w.done);
+
+	KUNIT_EXPECT_EQ(test, exec_after, exec_before);
+	KUNIT_EXPECT_GT(test, pelt_after, pelt_before);
+}
+
+struct pe_ctx {
+	/* Held by owner so holder blocks as a PROXY_EXEC donor. */
+	struct mutex mtx;
+	struct rw_semaphore sem;
+	struct completion mtx_locked;
+	struct completion sem_locked;
+	struct completion holder_done;
+	struct completion owner_done;
+	bool saw_waiter;
+	int prio_after_unblock;
+	int prio_after_unlock;
+	unsigned long w_after_unblock;
+};
+
+static int pe_mutex_owner_fn(void *arg)
+{
+	struct pe_ctx *c = arg;
+	unsigned long deadline;
+
+	set_user_nice(current, 19);
+	mutex_lock(&c->mtx);
+	complete(&c->mtx_locked);
+	wait_for_completion(&c->sem_locked);
+
+	/* Stay runnable here while donor H blocks and ticks run. */
+	deadline = jiffies + msecs_to_jiffies(40);
+	while (time_before(jiffies, deadline)) {
+		cpu_relax();
+		cond_resched();
+	}
+	mutex_unlock(&c->mtx);
+	complete(&c->owner_done);
+	return 0;
+}
+
+static int pe_donor_holder_fn(void *arg)
+{
+	struct pe_ctx *c = arg;
+
+	set_user_nice(current, 19);
+	down_read(&c->sem);
+	complete_all(&c->sem_locked);
+	/* Block on mtx while holding sem (PE keeps us on_rq). */
+	mutex_lock(&c->mtx);
+	mutex_unlock(&c->mtx);
+
+	/*
+	 * After waking in place, stay runnable and wait for the tick to
+	 * boost us via the rq->rwsem_holders link kept across blocking.
+	 */
+	c->saw_waiter = wait_for_rwsem_waiter(&c->sem, 500);
+	spin_wait_boost_prio(NICE_TO_PRIO(-10), 500);
+	c->prio_after_unblock = current->rwsem_boost.prio;
+	c->w_after_unblock = current->se.load.weight;
+	up_read(&c->sem);
+	c->prio_after_unlock = current->rwsem_boost.prio;
+	complete(&c->holder_done);
+	return 0;
+}
+
+static void test_proxy_exec_blocked_donor(struct kunit *test)
+{
+	int cpu = cpumask_first(cpu_online_mask);
+	struct task_struct *owner, *holder;
+	struct pe_ctx *c;
+	unsigned long w10;
+
+	if (!IS_ENABLED(CONFIG_SCHED_PROXY_EXEC))
+		kunit_skip(test, "needs CONFIG_SCHED_PROXY_EXEC");
+
+	c = kunit_kzalloc(test, sizeof(*c), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_NULL(test, c);
+	mutex_init(&c->mtx);
+	init_rwsem(&c->sem);
+	init_completion(&c->mtx_locked);
+	init_completion(&c->sem_locked);
+	init_completion(&c->holder_done);
+	init_completion(&c->owner_done);
+
+	set_user_nice(current, -10);
+	w10 = current->se.load.weight;
+
+	owner = kthread_run_on_cpu(pe_mutex_owner_fn, c, cpu,
+				   "rwsem_pe_own/%u");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, owner);
+	wait_for_completion(&c->mtx_locked);
+
+	holder = kthread_run_on_cpu(pe_donor_holder_fn, c, cpu,
+				    "rwsem_pe_hld/%u");
+	if (IS_ERR(holder)) {
+		complete_all(&c->sem_locked);
+		wait_for_completion(&c->owner_done);
+		KUNIT_FAIL(test, "failed to start PE holder");
+		return;
+	}
+	wait_for_completion(&c->sem_locked);
+
+	down_write(&c->sem);
+	up_write(&c->sem);
+	wait_for_completion(&c->holder_done);
+	wait_for_completion(&c->owner_done);
+
+	KUNIT_EXPECT_TRUE(test, c->saw_waiter);
+	KUNIT_EXPECT_EQ(test, c->prio_after_unblock, NICE_TO_PRIO(-10));
+	KUNIT_EXPECT_EQ(test, c->w_after_unblock, w10);
+	KUNIT_EXPECT_EQ(test, c->prio_after_unlock, MAX_PRIO);
+}
+
+static struct kunit_case rwsem_sched_boost_test_cases[] = {
+	KUNIT_CASE(test_basic_hold_and_release),
+	KUNIT_CASE(test_interleaved_unlock),
+	KUNIT_CASE(test_recursive_read_and_untrack),
+	KUNIT_CASE(test_overflow_graceful),
+	KUNIT_CASE(test_downgrade_write),
+	KUNIT_CASE_PARAM(test_wakeup_boost, wakeup_gen_params),
+	KUNIT_CASE(test_waiter_prio_packing),
+	KUNIT_CASE(test_queued_reader_slot),
+	KUNIT_CASE_SLOW(test_preemption_inversion_latency),
+	KUNIT_CASE(test_no_boost_uncontended),
+	KUNIT_CASE(test_renice_boosted_holder),
+	KUNIT_CASE(test_class_switch_clears_and_reboosts),
+	KUNIT_CASE(test_transitive_boost_chain),
+	KUNIT_CASE(test_reweight_updates_pelt),
+	KUNIT_CASE(test_proxy_exec_blocked_donor),
+	KUNIT_CASE_SLOW(test_fastpath_overhead),
+	{}
+};
+
+/* Cases that turn the boost off may abort: always turn it back on. */
+static void rwsem_boost_test_exit(struct kunit *test)
+{
+	rwsem_boost_set(true);
+}
+
+static struct kunit_suite rwsem_sched_boost_test_suite = {
+	.name = "rwsem_sched_boost",
+	.exit = rwsem_boost_test_exit,
+	.suite_init = rwsem_boost_suite_init,
+	.suite_exit = rwsem_boost_suite_exit,
+	.test_cases = rwsem_sched_boost_test_cases,
+};
+
+kunit_test_suite(rwsem_sched_boost_test_suite);
+
+MODULE_LICENSE("GPL");
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 2d22638ec13a..5294aacbb945 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -1692,6 +1692,23 @@ config WW_MUTEX_SELFTEST
 	  Say M if you want these self tests to build as a module.
 	  Say N if you are unsure.
 
+config RWSEM_SCHED_BOOST_KUNIT_TEST
+	bool "KUnit tests for rwsem scheduler priority boost" if !KUNIT_ALL_TESTS
+	depends on KUNIT=y && RWSEM_SCHED_BOOST
+	default KUNIT_ALL_TESTS
+	help
+	  This builds KUnit tests for per-task rw_semaphore hold tracking,
+	  the waiter priority packed into sem->count and the scheduler
+	  boost of contended holders.  The tests are built in because they
+	  call unexported rwsem and scheduler helpers.  Boot with
+	  rwsem_sched_boost_test.benchmark=1 to also run the fastpath
+	  benchmark.
+
+	  For more information on KUnit and unit tests in general, please
+	  refer to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+	  If unsure, say N.
+
 config SCF_TORTURE_TEST
 	tristate "torture tests for smp_call_function*()"
 	depends on DEBUG_KERNEL
-- 
2.56.1.839.g22a8290db9-goog


^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [RFC PATCH v2 2/6] btrfs: untrack i_rwsem before io_uring encoded read completion
  2026-12-01  6:27 ` [RFC PATCH v2 2/6] btrfs: untrack i_rwsem before io_uring encoded read completion Peng Huang
@ 2026-12-01  8:40   ` Christoph Hellwig
  2026-12-01 14:43     ` Steven Rostedt
  0 siblings, 1 reply; 9+ messages in thread
From: Christoph Hellwig @ 2026-12-01  8:40 UTC (permalink / raw)
  To: Peng Huang
  Cc: Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng, Juri Lelli,
	Vincent Guittot, Waiman Long, Dietmar Eggemann, Steven Rostedt,
	Ben Segall, Mel Gorman, Valentin Schneider, K Prateek Nayak,
	John Stultz, Suren Baghdasaryan, linux-kernel, linux-mm,
	David Sterba, Chris Mason, linux-btrfs

I only see patch 2 on the btrfs list, so something got really messed up
in your patch sending.

On Mon, Nov 30, 2026 at 10:27:29PM -0800, Peng Huang wrote:
> diff --git a/fs/btrfs/ioctl.c b/fs/btrfs/ioctl.c
> index 6ba883db107b..073450a6df95 100644
> --- a/fs/btrfs/ioctl.c
> +++ b/fs/btrfs/ioctl.c
> @@ -4725,6 +4725,13 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter,
>  	priv->lockend = lockend;
>  	priv->err = 0;
>  
> +	/*
> +	 * Once the reads are queued, btrfs_uring_read_finished() may
> +	 * unlock i_rwsem from another task, so stop tracking it as held
> +	 * by this one.  On error the caller's unlock finds no record.
> +	 */
> +	rwsem_boost_untrack(&inode->vfs_inode.i_rwsem);

I don't think this is a good interface (and it looks like you're adding
it given no existing in-tree matches).

Currently there's a gazillion different things that need to be done
for handing off locks and releasing them in other threads including
lockdep fake release/acquire annotations, hacks to make it shut off when
returning to userspace, etc.  Which is sad, as in I/O and file system
land the idea of taking a lock and handing it to a different completion
path makes perfect sense.

But we need a better interface for that, something like a disown just
before returning to userspace or the caller, and a "take ownership"
called as early as possible from the completion callback.  Let's build
such a proper highlevel interface and make it all the right things
instead of encoding implementation details all over the tree.


^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [RFC PATCH v2 2/6] btrfs: untrack i_rwsem before io_uring encoded read completion
  2026-12-01  8:40   ` Christoph Hellwig
@ 2026-12-01 14:43     ` Steven Rostedt
  0 siblings, 0 replies; 9+ messages in thread
From: Steven Rostedt @ 2026-12-01 14:43 UTC (permalink / raw)
  To: Christoph Hellwig
  Cc: Peng Huang, Peter Zijlstra, Ingo Molnar, Will Deacon, Boqun Feng,
	Juri Lelli, Vincent Guittot, Waiman Long, Dietmar Eggemann,
	Ben Segall, Mel Gorman, Valentin Schneider, K Prateek Nayak,
	John Stultz, Suren Baghdasaryan, linux-kernel, linux-mm,
	David Sterba, Chris Mason, linux-btrfs

On Tue, 1 Dec 2026 00:40:51 -0800
Christoph Hellwig <hch@infradead.org> wrote:

> I only see patch 2 on the btrfs list, so something got really messed up
> in your patch sending.

b4 and lore is your friend ;-)

/me ignores anything where I'm blasted with a patch series where I only
care about the one patch that affect me. I don't have time to read the rest.
If I want to know more, I use b4 and/or lore. It's really simple to use.

-- Steve

^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2026-12-01 14:43 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-12-01  6:27 [RFC PATCH v2 0/6] rwsem: priority boost for holders blocking high-priority waiters Peng Huang
2026-12-01  6:27 ` [RFC PATCH v2 1/6] locking/rwsem: Track held rwsems per task Peng Huang
2026-12-01  6:27 ` [RFC PATCH v2 2/6] btrfs: untrack i_rwsem before io_uring encoded read completion Peng Huang
2026-12-01  8:40   ` Christoph Hellwig
2026-12-01 14:43     ` Steven Rostedt
2026-12-01  6:27 ` [RFC PATCH v2 3/6] locking/rwsem: Publish the top waiter priority Peng Huang
2026-12-01  6:27 ` [RFC PATCH v2 4/6] sched: Apply rwsem holder boost to the fair load weight Peng Huang
2026-12-01  6:27 ` [RFC PATCH v2 5/6] sched/fair: Boost rwsem holders with contended high-priority waiters Peng Huang
2026-12-01  6:27 ` [RFC PATCH v2 6/6] locking/rwsem: Add KUnit tests for scheduler priority boost Peng Huang

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®