From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.161.69 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796106472; b=nlHaWl3GvgMuVk+5Ou4PnqdBGyo/hr8lhnGGPDb5gtz58gTl1qqEX5qN5QWKjK+gpI6x 2CmvToxVogDX1VdgsE06W8nXU6/wfXC/BkPza4JE5/47TAPOGBF2hwECXf+NPKh7taXxS GPvou1ReJw+R3BNJp/vdXIZKZF7FG0J8X9BmFQbj5Fj73lDGxkDtcGsyVwP9KsC4g3ekf q+1Lp8U5i3ttKSAc/Vf26YxL6nnI3kQpye2yGeBGysABLuVKCoxmPpSOGcbkPJ93eN+A0 5h7OTkJlM7LjmmyvjITzwdLLYgWMsPiZhZDGMthbRi/qCF+ZCTeLRHD5SBAVPP4hSaw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796106472; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=c7cWhofKCUy5v+5Fu1JwgSodpp7hmMqZsAwrDfgOtWg=; b=wSDGD3CQPyhZ1UxVVOvRhU/UYIRTt18u7kyhlCRC+zmSK+gjA1r8U1txcF2KEbM5YMBx SbH8oTyVEE9EG+2S0njDJXt+aNJt+9CXbuqK1+kjni0Ul4PsS+am5+pV+aQk3NAB/5LGo Z0apA3E15fX7tylW2tt6F+25neVeZiwjvOWwELPH4IewCLiQ6N5/N1qXEg2IV88I5vHxm 953bAgl95ypMrEkqABveqskF1FUWHdqyVqvwvp7UB2Rclq4l+MyC6Wsfa7g6aU4Gvl9Ig HXH0Fn9cu9ZKJnvRMMTaRUnQlIF4oppA0E3wfpiGYN5gROZkjECXW+/fLIt4QfBtHKw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--penghuang.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Ldt7Ypj3; arc=none smtp.remote-ip=209.85.161.69 Received: from mail-oo1-f69.google.com (mail-oo1-f69.google.com [209.85.161.69]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5E8CD606A6AC for ; Tue, 1 Dec 2026 06:27:51 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 5E8CD606A6AC Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--penghuang.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=Ldt7Ypj3 Received: by mail-oo1-f69.google.com with SMTP id 006d021491bc7-71ade585746so5453627eaf.0 for ; Mon, 30 Nov 2026 22:27:51 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1796106470; x=1796711270; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=c7cWhofKCUy5v+5Fu1JwgSodpp7hmMqZsAwrDfgOtWg=; b=Ldt7Ypj30DctfSYsChPrzCAwv9Ug0UV9cQOmVo6l4pIVpMdD1FdBffJ1ayP2yPhXGq TW8akjioCaMUXIf1VK4h9fM4oOwYkkv14v15WWp/aEXuxSEvlqbTs4zebHJRe9k0kZJA q56dgcMapWXS2OCZIHnhlzRtI18RFaFI3xRaZXKIrrEqPavPZobnblKlSjDcC1XSoKO7 eAK7XGiTTa8iAIr4YbOpxEjN01x4OcpaWlF7weXFN43DHQiksHuYBhQf5qgavBEMRIVk Kky043iDOKajUs0f+AZPVAoSeTqKjwVR+N3kamm/aK7utTOtxkv4L25g0Ww6cvYNvEM+ mfLg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796106470; x=1796711270; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=c7cWhofKCUy5v+5Fu1JwgSodpp7hmMqZsAwrDfgOtWg=; b=lq2g9VHUHHNlMJubFflOoPGMWZK1IJ2m22c58Le3RasELYGgfCDFQzOiAuUlyLqmA9 2j9h+c5KinY+GgpIHnCxbmEGy5u2vEVqxnRbQx82Dgrzd6XwDoqHvoTCtTO9SIdbk5v6 uHpR3Pubi/WIEIll10J1PbptC2vI3J6DRSwSzfYMc6WJcXPxHYmfEA3Lib6icw6ut1Jk QHOOoi3/faGfPDUeHW/M4tfrPW++dhL5KBtfMPyUHhBP9OzCIplawYefRlgOj4+tEdSW LDmsapd9qzooQOXmpY/h3fKNOLvYS66VlQAj88OK7TKx2206/OmDh4fwMT4r6KH6NUiV sYXw== X-Forwarded-Encrypted: i=1; AL+hErFv/L5Lh3IJ1ao9As0NeCj2EOduRXMirvltm1BuejTGmGQ4XhthMB/LEnwOKoCJzEzXMFTSocyvGL+aPSk=@vger.kernel.org X-Gm-Message-State: APuU4Z+50WnS29yneaXEUiIbzfQAtUONJQ3O88SVKYewWJzLkO0oQnMK N25KElyBUCgqEFRQmeVbn9K6z49jE0T62oFuvT8VT3NFS6ivGPvbG7HnsaLTh7SobCGsJuk4JZw vXqjWxKWTAFabOqRtyg== X-Received: from oahs23-n2.prod.google.com ([2002:a05:6871:8897:20b0:49f:2b22:bea]) (user=penghuang job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6820:a28d:10b0:6f8:3d45:b469 with SMTP id 006d021491bc7-71b395b4595mr21169406eaf.86.1796106469857; Mon, 30 Nov 2026 22:27:49 -0800 (PST) Date: Mon, 30 Nov 2026 22:27:33 -0800 In-Reply-To: <20261201062738.1047159-1-penghuang@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261201062738.1047159-1-penghuang@google.com> X-Mailer: git-send-email 2.56.1.839.g22a8290db9-goog Message-ID: <20261201062738.1047159-7-penghuang@google.com> Subject: [RFC PATCH v2 6/6] locking/rwsem: Add KUnit tests for scheduler priority boost From: Peng Huang 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@vger.kernel.org, linux-mm@kvack.org, Peng Huang , Andrew Morton Content-Type: text/plain; charset="UTF-8" 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 --- 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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(¤t->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