mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Peng Huang <penghuang@google.com>
To: Peter Zijlstra <peterz@infradead.org>,
	Ingo Molnar <mingo@redhat.com>,  Will Deacon <will@kernel.org>,
	Boqun Feng <boqun@kernel.org>, Juri Lelli <juri.lelli@redhat.com>,
	 Vincent Guittot <vincent.guittot@linaro.org>
Cc: Waiman Long <longman@redhat.com>,
	Dietmar Eggemann <dietmar.eggemann@arm.com>,
	 Steven Rostedt <rostedt@goodmis.org>,
	Ben Segall <bsegall@google.com>, Mel Gorman <mgorman@suse.de>,
	 Valentin Schneider <vschneid@redhat.com>,
	K Prateek Nayak <kprateek.nayak@amd.com>,
	 John Stultz <jstultz@google.com>,
	Suren Baghdasaryan <surenb@google.com>,
	linux-kernel@vger.kernel.org,  linux-mm@kvack.org,
	Peng Huang <penghuang@google.com>,
	Jonathan Corbet <corbet@lwn.net>,
	 Shuah Khan <skhan@linuxfoundation.org>,
	Randy Dunlap <rdunlap@infradead.org>,
	 Sebastian Andrzej Siewior <bigeasy@linutronix.de>,
	Clark Williams <clrkwllms@kernel.org>,
	linux-doc@vger.kernel.org,  linux-rt-devel@lists.linux.dev
Subject: [RFC PATCH v2 1/6] locking/rwsem: Track held rwsems per task
Date: Mon, 30 Nov 2026 22:27:28 -0800	[thread overview]
Message-ID: <20261201062738.1047159-2-penghuang@google.com> (raw)
In-Reply-To: <20261201062738.1047159-1-penghuang@google.com>

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


  reply	other threads:[~2026-12-01  6:27 UTC|newest]

Thread overview: 8+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
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 [this message]
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  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

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261201062738.1047159-2-penghuang@google.com \
    --to=penghuang@google.com \
    --cc=bigeasy@linutronix.de \
    --cc=boqun@kernel.org \
    --cc=bsegall@google.com \
    --cc=clrkwllms@kernel.org \
    --cc=corbet@lwn.net \
    --cc=dietmar.eggemann@arm.com \
    --cc=jstultz@google.com \
    --cc=juri.lelli@redhat.com \
    --cc=kprateek.nayak@amd.com \
    --cc=linux-doc@vger.kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-mm@kvack.org \
    --cc=linux-rt-devel@lists.linux.dev \
    --cc=longman@redhat.com \
    --cc=mgorman@suse.de \
    --cc=mingo@redhat.com \
    --cc=peterz@infradead.org \
    --cc=rdunlap@infradead.org \
    --cc=rostedt@goodmis.org \
    --cc=skhan@linuxfoundation.org \
    --cc=surenb@google.com \
    --cc=vincent.guittot@linaro.org \
    --cc=vschneid@redhat.com \
    --cc=will@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
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®